2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Shell scriptノウハウ集(覚え書き)

Posted at

Shell scriptノウハウ集(覚え書き)

if文で"Invalid Numeric Literal", "unary operator expected", "too many arguments"エラーが出る場合

変数がnullになっている可能性

  • 【原因】 コマンドの結果がnullになる可能性がある。
  • 【結果】if文中の$varがnullなので、if文が壊れてしまい、Invalid Numeric Literalエラーが発生。
var=`コマンド`
if [ $var != "" ]; then
    echo "YES"
fi
  • 【修正方法】変数名を""で囲う。
var=`コマンド`
if [ "$var" != "" ]; then
    echo "YES"
fi

for文の書き方

  • 基本構文
for 変数 in 値リスト
do
  処理
done
  • コマンドの実行結果でループ
for var in `コマンド`
do
  処理
done
  • 一定回数(N回)ループ
for i in `seq 1 N`
do
  echo "$i 回目のループです。"
done

for文では、continueおよびbreakが使用可能。

while文の書き方

  • 基本構文
while 条件式
do
   処理
done
  • testコマンドを使用する
while [ 条件式 ]
do
   処理
done
  • コマンドの実行結果を使用する
    read lineの終了ステータスが1となり、条件式が偽となることでwhileループが終了する。
while read line
do
  echo "$line"
done <test.txt
  • 無限ループ
while :
do
  処理
  if 条件式; then
    break
  fi
  処理
done

入力待ち

printf "TTY1: ";read TTY1
echo $TTY

ファイルを読み込んで行処理

files=`cat servers.txt`
for server in $files
do
    echo $server
done
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?