スクリプト

スクリプト

これは可能ですか(bash v5.0.3)?

追加のコードの再利用とスクリプト自動化のために、連想配列のキーを使用して選択リストを動的に入力したいと思います。一部のキーにはスペースのみが必要です。私は私の問題を次のように分離したようです。choices="${!playlist_url[@]}" # Need quoted key expansion here, but choices="${!playlist_url[@]@Q} does nothing"

私のスクリプトは次のとおりです。 「1)」の後にすべてのアップローダが接続され、印刷された選択オプションが表示されます。私が達成できる最善の方法は、キーを$ choicesの一重引用符で囲み、引用符の外に出すことです。choices=("Quit ${choices@Q}")

スクリプト


# Creates the array
declare -A playlist_url

# Sets the field separator to comma and reads in the uploader & url
## EXAMPLES: from ~/.config/youtube-dl/playlists-hcs7 ##
# UploaderName,https://www.youtube.com/playlist?list=xx...xx
# Uploader Name,https://www/youtube.com/playlist?list=xx...xx
# Up Loader Name,https://www/youtube.com/playlist?list=xx...xx

while IFS=\, read -p "uploader,url" uploader url
do
    playlist_url[$uploader]="$url"
done <~/.config/youtube-dl/playlists-hcs7

#unset IFS  <--Ignore my trying to better understand the IFS
#IFS=       <--"      "
choices=${!playlist_url[@]}  # Need quoted key expansion here (I think!)
choices=("Quit ${choices}") # Prepending 'Quit' for case break below

clear

PS3="Make a selection: "

select option in "$choices";
do
    case $option in
        "Quit")
            echo "Exiting."
            break
            ;;
        *)
            echo "Debug: $option"
            # Do stuff
            ;;
    esac
done

使用されたリソース

  • バッシュマンページ
  • 検索エンジンで数多くの書き換え
  • 役に立つ回答/質問範囲は似ていますが、適用方法は異なります。

つまり、リンクされた回答の編集内容は次のようになります。

編集:この質問に答えてから約5年後、bash 4.4がリリースされました。これには、bashで再解析できるように変数を参照する拡張子「${var@Q}」があります。

ベストアンサー1

おすすめ記事