入力パラメータとしての文字列

入力パラメータとしての文字列

たとえば、複数の文字列を入力として受け入れる関数があるとしますls

test 1さらに、などのスペースを持つ2つのフォルダがありますtest 2

電話すると、ls "test 1" "test 2" ls両方のフォルダの内容が一覧表示されます。

リストしたいフォルダ自体が次の文字列にあるとしましょうfolders="\"test 1\" \"test 2\""

最後に、この変数を入力パラメータとして使用したいと思いますls。どうすればいいですか?私はls $folders戻ろうとしました:

ls: cannot access '"test': No such file or directory
ls: cannot access '1"': No such file or directory
ls: cannot access '"test': No such file or directory
ls: cannot access '2"': No such file or directory

つまり、引用符が文字列を一緒に保持する必要がある場合でも、文字列を別の引数に分割します。この問題を解決するためのオプションは何ですか?使いやすい場合は、パラメータを配列として提供できます。

ベストアンサー1

jesse_bが述べたように、ここでは配列を使用する必要があります。 bashdeclareコマンドはとても便利です。

folders="\"test 1\" \"test 2\"".
declare -a "dirs=($folders)"
declare -p dirs          # inspect the variable

出力

declare -a dirs=([0]="test 1" [1]="test 2.")

次のように配列を使用できます(引用符が重要です)。

ls "${dirs[@]}"

おすすめ記事