144
119

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 1 year has passed since last update.

Bashでいろいろループする

Last updated at Posted at 2016-05-19

配列をハードコーディングしてループ

items=(
    "altair"
    "betelgeuse"
    "canopus"
)

for item in "${items[@]}" ; do
    echo "[ ${item} ]"
done

ハードコーディング パターン2

items[0]="altair"
items[1]="betelgeuse"
items[2]="canopus"

for item in "${items[@]}" ; do
    echo "[ ${item} ]"
done

連番を生成してループ

for i in {1..10} ; do
    echo ${i}
done
for i in `seq 1 10`; do
    echo ${i}
done

ファイル一覧をループ

for file_name in * ;do
    echo ${file_name}
done
files=(`ls -1 somedir/`)
for file_name in "${files[@]}"; do
    echo ${file_name}
done

引数をすべてループ

for arg; do
  echo ${arg}
done
for arg in "$@"; do
  echo ${arg}
done
$ ./hoge.sh altair betelgeuse canopus

Thanks to: @akinomyoga, @mpyw

ファイルを読み込んで1行づつループ

while read line ; do
    echo ${line}

done < ${DATAFILE}

二次元表

#!/usr/bin/env bash

# iOS 公開用に PNG 画像のアイコンサイズを変更するスクリプト

sizes=(
"29 29"
"40 40"
"50 50"
"57 57"
"58 29@2x"
"60 60"
"72 72"
"76 76"
"80 40@2x"
"87 29@3x"
"100 50@2x"
"114 57@2x"
"120 60@2x"
"144 72@2x"
"152 76@2x"
"167 83.5@2x"
"180 60@3x"
)

if [ ! "${1}" ]; then
    echo "usage: ${0} <image-file>"
    exit 1
fi

bn=`basename ${1}`
bn=${bn%.*}
DN=`dirname ${1}`
for size in "${sizes[@]}"; do
    s=(${size})
    out_file=${bn}_${s[1]}.png
    echo ${s[0]} ${out_file}
    # sips --resampleWidth ${s[0]} --out ${out_file} ${1}
    convert -resize ${s[0]}x ${1} ${out_file}
done

zsh の場合

#!/usr/bin/env zsh

# ↓これを書いておく
setopt SH_WORD_SPLIT

servers=(
  "1 user@server1.example.com"
  "2 user@server2.example.com"
)

for row in "${servers[@]}"; do
  echo '========================'
  s=(${row})
  echo ${s[1]}
  echo ${s[2]}
done

結果

========================
1
user@server1.example.com
========================
2
user@server2.example.com
144
119
2

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
144
119

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?