[英]How do I iterate through positional variables in bash?
用戶將給出他們想要的任意數量的位置參數(都是C程序)。 我想這樣做,以便所有C程序都能編譯。 但是,這是行不通的。 有沒有人有辦法解決嗎?
echo '#!/bin/bash' >> compile
echo if [ "-o"='$1' ] >> compile
echo then >> compile
echo for (i=3; i<='$#'; i++) >> compile
echo do >> compile
echo gcc -o '$2' '${i}' >> compile
echo fi >> compile
不要使用一堆echo
語句,請使用here-doc。 在<<
后面加上引號,可防止在here-doc中擴展變量。
cat <<'EOF' >>compile
'#!/bin/bash'
if [ "-o" = "$1" ]
then
for ((i=3; i <= $#; i++))
do
gcc -o "$2" "${!i}"
done
fi
EOF
否則,您需要轉義或引用所有特殊字符-由於未在for()
行中的<
轉義,所以您遇到了錯誤。
其他錯誤:您需要在[
命令中的=
周圍加上空格,並且在for
循環的末尾缺少done
的代碼。 要間接訪問變量,您需要使用${!var}
語法。
遍歷所有參數的通常方法是使用簡單的方法:
for arg
環。 當for variable
沒有in
之后時,它將遍歷參數。 您只需要先刪除-o outputfile
參數即可:
output=$2
shift 2 # remove first 2 arguments
for arg
do
gcc -o "$output" "$arg"
done
這是我將如何編輯您最初發布的內容:
$ cat test.sh
echo -e "#!/bin/bash" > compile.sh
echo -e "if [ \"\${1}\" == \"-o\" ]; then" >> compile.sh
echo -e "\tlist_of_arguments=\${@:3} #puts all arguments starting with \$3 into one argument" >> compile.sh
echo -e "\tfor i in \${list_of_arguments}; do" >> compile.sh
echo -e "\t\techo \"gcc \${1} '\${2}' '\${i}'\"" >> compile.sh
echo -e "\tdone" >> compile.sh
echo -e "fi" >> compile.sh
$ ./test.sh
$ cat compile.sh
#!/bin/bash
if [ "${1}" == "-o" ]; then
list_of_arguments=${@:3} #puts all arguments starting with $3 into one argument
for i in ${list_of_arguments}; do
echo "gcc ${1} '${2}' '${i}'"
done
fi
$ chmod +x compile.sh
$ ./compile.sh -o one two three four five
gcc -o 'one' 'two'
gcc -o 'one' 'three'
gcc -o 'one' 'four'
gcc -o 'one' 'five'
為了進行演示,我在test.sh
回顯了gcc
命令。 要實際運行gcc而不是回顯它,請將test.sh
第五行更改為:
echo -e "\t\techo \"gcc \${1} '\${2}' '\${i}'\"" >> compile.sh
至
echo -e "\t\tgcc \${1} '\${2}' '\${i}'" >> compile.sh
或將回聲通過管道傳遞給sh,如下所示:
echo -e "\t\techo \"gcc \${1} '\${2}' '\${i}'\" \| sh" >> compile.sh
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.