ikeh1024のブログ

ZennやQiitaに書くにはちょっと小粒なネタをこちらに書いています

ShellScriptのメモ書き_01

概要を知りたいときに見るページ

シェルスクリプトの実行

bash <ファイル名>.command

配列の作成で縦に並べたい

  • ("A" "B" "C")と横に並べず、複数行にするなら以下の書き方一択なのだろうか。
files=()
files=("${files[@]}" "text1.txt")
files=("${files[@]}" "text2.txt")
files=("${files[@]}" "text3.txt")

エラーsyntax error near unexpected token doの対処

  • 改行コードがCRLFが原因なんだとか。
  • CotEditorなどでLFにしてやると治った。
bash /Desktop/Sample/myscript.command 
/Desktop/Sample/myscript.command: line 10: syntax error near unexpected token `do
/Desktop/Sample/myscript.command: line 10: `for file in "${files[@]}"; do

出力を非表示にする方法

mv -f "${dir}/${file}" /tmp/ > /dev/null 2>&1

シェル — スペースが含まれる配列要素をループする

Bashの配列の要素をそれぞれ個別の引数として扱う場合は、ダブルクォートで囲って、"${arr[@]}" とすれば大丈夫です。$@ の展開と同じ事情です。

sh for item in "${arr[@]}"; do

  • 通常だと分割して認識されてしまう
#!/bin/sh
files=()
files=("${files[@]}" "text with space.txt")

for file in ${files[@]}; do
    echo "${dir}/${file}" 
done
/text
/with
/space.txt
  • ダブルコーテーションでくくって、1つのものとして認識させる
#!/bin/sh
files=()
files=("${files[@]}" "text with space.txt")

for file in "${files[@]}"; do
    echo "${dir}/${file}" 
done
/text with space.txt