使用list / array作为参数调用bash脚本

时间:2015-05-04 20:04:28

标签: bash

是否可以使用数组/列表作为参数之一调用bash脚本?我已经尝试了下面的例子,但它在“(”。我试图得到3美元,为我的脚本分配了一个列表。

bash file_manipulation.sh source_dir target_dir (filename1 filename2)

3 个答案:

答案 0 :(得分:5)

这样做:保存前2个参数并将它们移出位置参数,然后将剩余的位置参数存储在数组中

#!/bin/bash

src=$1
tgt=$2
shift 2
files=( "$@" )

echo "manipulation"
echo " src=$src"
echo " tgt=$tgt"
for ((i=0; i < ${#files[@]}; i++)); do
    echo " file $i: ${files[i]}"
done

所以

$ bash file_manipulation.sh source_dir target_dir filename1 filename2
manipulation
 src=source_dir
 tgt=target_dir
 file 0: filename1
 file 1: filename2

您也可以像阵列一样使用位置参数:

for file do
    echo file: $file
done

答案 1 :(得分:2)

不,您只能将字符串传递给shell脚本(或者其他任何程序)。

但是,您可以做的是为自己定义的数组处理一些特殊语法,并在shell脚本中手动解析。例如,您可以使用括号作为数组的分隔符。然后,您必须转义它们,以便它们不被shell解释:

bash file_manipulation.sh source_dir target_dir \( filename1 filename2 \)

答案 2 :(得分:2)

cat file_manipulation.sh 
#!/bin/bash
echo -e "source:\n  $1";
echo -e "target:\n  $2";
echo "files:";
#Convert a String with spaces to array, before delete parenthesis
my_array=(`echo $3 | sed 's/[()]//g'`)
for val in ${my_array[@]}; do
  echo "  $val";
done

#I add quotes to argument
bash file_manipulation.sh source_dir target_dir "(filename1 filename2)"

你得到:

source:
  source_dir
target:
  target_dir
files:
  filename1
  filename2

注意:没有括号

会更好
cat file_manipulation.sh 
#!/bin/bash
my_array=( $3 )
for val in ${my_array[@]}; do
  echo "$val";
done

#I add quotes to argument, and without parenthesis
bash file_manipulation.sh source_dir target_dir "filename1 filename2"

注2:文件名不能包含空格。