(2024-06-06 å稿)
Bashã«ãã¤ããã¥ã¡ã³ããããã®ã¯ç¥ã£ã¦ãããããã¤ã¹ããªã³ã°ã¨ããã®ãããã®ãã¤ãæè¿ç¥ã£ãã
ãã¤ã¹ããªã³ã°ã使ã£ã¦ã¿ãã¨ã便å©ãªã®ã§åå¿é²ã¨ãã¦ã¢ããããã
ãã¤ããã¥ã¡ã³ã
ã¾ãã¯ããã¤ããã¥ã¡ã³ãã
$ cat << EOC
ãã¡ãã¯ããã¤ããã¥ã¡ã³ã
ãã¤ããã¥ã¡ã³ãã¯é·æã®å
¥åºåãªã©ã§ä¾¿å©ã«ä½¿ãã
EOC
ãã¡ãã¯ããã¤ããã¥ã¡ã³ã
ãã¤ããã¥ã¡ã³ãã¯é·æã®å
¥åºåãªã©ã§ä¾¿å©ã«ä½¿ãã
ä¸è¨ã®ããã«é·æã®å
¥åºåã§ä¾¿å©ã«ä½¿ããã
ãã¤ã¹ããªã³ã°
ç¶ãã¦ãæ¬é¡ã®ãã¤ã¹ããªã³ã°ã
ãã¤ã¹ããªã³ã°ã¯ãé·æã®æåçãå¤æ°ã«ä¿åããã
$ here_str=$(
cat << EOC
ãã¡ãã¯ããã¤ã¹ããªã³ã°
ãã¤ã¹ããªã³ã°ã使ãã¨ä¾¿å©ã«ãªã
ãã®è¨äºã§ã¯ããã¤ããã¥ã¡ã³ãã¨ãã¤ã¹ããªã³ã°ãæ±ã
EOC
)
ã¾ãã¯ããã£ã¨ç°¡åã«ããã«ã¯ã©ã¼ãã§è¤æãå¤æ°ã«å
¥åããã
here_str="ãã¡ãã¯ããã¤ã¹ããªã³ã°
ãã¤ã¹ããªã³ã°ã使ãã¨ä¾¿å©ã«ãªã
ãã®è¨äºã§ã¯ããã¤ããã¥ã¡ã³ãã¨ãã¤ã¹ããªã³ã°ãæ±ã"
ä¸è¨2ä¾ã®ã©ã¡ãããæååå¤æ°ãªã®ã§echoã³ãã³ãã§åºåã§ããã
ããã«ã¯ã©ã¼ãã§å²ãã å ´åã¯ãå¤æ°ãããã«ã¯ã©ã¼ãã§å²ããã¨ãå¿ããªãã§
echo "$here_str"
ãã¡ãã¯ããã¤ã¹ããªã³ã°
ãã¤ã¹ããªã³ã°ã使ãã¨ä¾¿å©ã«ãªã
ãã®è¨äºã§ã¯ããã¤ããã¥ã¡ã³ãã¨ãã¤ã¹ããªã³ã°ãæ±ã
ããã¾ã§ã®ã¨ããããã¤ããã¥ã¡ã³ãã¨ãã¤ã¹ããªã³ã°ã«éãã¯ãªãããã¤ã¹ããªã³ã°ã®ã¡ãªããã¯ä»ã®ã¨ããç¡ãã
ãã¤ã¹ããªã³ã°ã®ä¾¿å©ãªã¨ãã
ä»ã®ã¨ããæ°ã¥ãã¦ãããã¤ã¹ããªã³ã°ã®ã¡ãªããã¯ä»¥ä¸ã®ã¨ããã
- ãã¤ãã使ããã«ä¸æãã¤å¦çã§ãã
- readé¢æ°ã¨ä½µç¨ãããã¨ã«ãããå¼æ°çã®åã渡ãã楽ã«ãªã
以ä¸ãããããã解説ããã
ãã¤ãã使ããã«ä¸æãã¤å¦çã§ãã
以ä¸ã®ã¨ãããwhileã¨ã¨ãã«ä½¿ããã¨ã«ããããã¤ãã使ããã«1è¡ãã¤å¦çãããã¹ã¯ãªãããä½ããã¨ãã§ããã
here_str="ãã¡ãã¯ããã¤ã¹ããªã³ã°
ãã¤ã¹ããªã³ã°ã使ãã¨ä¾¿å©ã«ãªã
ãã®è¨äºã§ã¯ããã¤ããã¥ã¡ã³ãã¨ãã¤ã¹ããªã³ã°ãæ±ã"
while read line
do
 echo $line | sed "s/ãã¤/here/g"Â
done <<< "$here_str"
ãã¡ãã¯ãhereã¹ããªã³ã°
hereã¹ããªã³ã°ã使ãã¨ä¾¿å©ã«ãªã
ãã®è¨äºã§ã¯ãhereããã¥ã¡ã³ãã¨hereã¹ããªã³ã°ãæ±ã
ãã¤ãã使ãã¨ããµãã·ã§ã«ã®åä½ã¨ãªããé¢æ°å
ã§ã®ã°ãã¼ãã«å¤æ°ã®å¤æ´ã§ããªãçã®ç½ ãåé¿ãããã¨ãã§ããã
readé¢æ°ã¨ä½µç¨ãããã¨ã«ãããå¼æ°çã®åã渡ãã楽ã«ãªã
ãã¡ãã®æ¹ãã¡ãªããã大ããã¨æãããããreadé¢æ°ãå©ç¨ãããã¨ã«ãããé¢æ°ã¸ã®å¼æ°ã®åã渡ããæã®é
åã¸ã®å
¥åãæ ¼æ®µã«ä¾¿å©ã«ãªãã
arg_str="arg1 arg2 arg3"
read -a line_ary <<< "$arg_str"
echo ${line_ary[0]}
echo ${line_ary[1]}
echo ${line_ary[2]}
arg1
arg2
arg3
readã« -a ãªãã·ã§ã³ãä»ãããã¨ã«ãããé
å(line_ary)ã«IFSã§æååãåºåã£ã¦å
¥ãããã¨ãã§ããã
ãããå¤æ°ãã¹ãã¼ã¹ã§ãªããã«ã³ã(,)çã§åºåããã¦ããå ´åã§ããIFSãä¸æçã«å¤æ´ãã¦èªã¿è¾¼ãã°è¯ãã
arg_str="arg1,arg2,arg3"
IFS=, read -a line_ary <<< "$arg_str"
for s in "${line_ary[@]}" # forã«ã¼ãã§é
åã®è¦ç´ ãä¸ã¤ãã¤
do
 echo "$s"
done
echo $IFS    #IFSãå¤æ´ãããªããã¨ã®ç¢ºèª
arg1
arg2
arg3
æ·»ãåãå¿
è¦ãªå ´åã¯ã"${!line_ary[@]}"ã®ããã«æ·»ãåã®ãªã¹ãã®é
åããä¸ã¤ãã¤forã§åãåºãã¨ä¾¿å©ã
for i in "${!line_ary[@]}"
do
 echo "$i => ${line_ary[$i]}"
done
0 => arg1
1 => arg2
2 => arg3
以ä¸ã®ããã«ãæååãä»»æã®åºåãæå(IFS)ã§é
åã«ãããã¨ã容æã«ãªãã
å¤æ°ã®å¼æ°ãé¢æ°ã«æ¸¡ãå ´åãªã©ã¯ããã¤ã¹ããªã³ã°ãå¼æ°ã¨ããé¢æ°å
ã§é
åã«ããæ¹ã便å©ã ã¨æãããã
åèã¾ã§ã«ãä¸è¨ãå©ç¨ãã¦ä½æããã¹ã¯ãªããã以ä¸ã®ãã¼ã¸ã«ããã®ã§ãèå³ãããæ¹ã¯ã覧ã«ãªã£ã¦ã
以ä¸ãã©ãªããã®åèã«ãªãã°å¹¸ãã
é¢é£ãã¼ã¸