目录名称 Bash 中的空格

目录名称 Bash 中的空格

我是 bash 新手,正在编写遍历 tar.gz 文件存档的脚本,并在每个文件中将指定的字符串更改为另一个字符串。脚本参数:存档名称、搜索字符串、目标词。我的问题是,当存档名称包含空格时(例如,我使用以下参数运行脚本:>change_strings.sh“/tmp/tmp.m7xYn5EQ2y/work/data txt”a A)我有以下错误:在线if [ ! -f $filename ] ; then [:数据:需要二元运算符,目录名:额外操作数“txt”。这是我的代码:

  #!/bin/bash 
  filename="${1##*/}"
  VAR="$1"
  DIR=$(dirname ${VAR})
  cd "$DIR"


if [ ! -f $filename ] ; then
echo "no such archive" >&2
exit 1
fi


if ! tar tf $filename &> /dev/null; then
echo "this is not .tar.gz archive" >&2
exit 1
fi


dir=`mktemp -dt 'test.XXXXXX'`
tar -xf $filename -C $dir  #extract archive to dir
cd $dir #go to argument directory

FILES=$dir"/*"

for f in $FILES
do
sed -i "s/$2/$3/g" "$f"
done

tar -czf $filename * #create tar gz archive with files in current directory
mv -f $filename $cdir"/"$filename #move archive
rm -r $dir #remove tmp directory

答案1

你应该把你的放在$filename双引号中:"$filename"

相关内容