Shell:如何处理在shell脚本中包含`\n`或``的文件名

MrR*_*ROY 1 bash shell

我有这样的shell脚本:

#!/bin/bash
if [ $# -lt 1 ]
then
  echo "Use: "$0" <file_name>"
  echo "Convert files from GBK to UTF8"
  exit
fi

for i in $*

  # Generate temp file to avoid Bus error
  iconv -f GBK -t utf-8 "$i" -o "$i.tmp"
  mv "$i.tmp" "$i"
done
Run Code Online (Sandbox Code Playgroud)

问题是$i可以含有\n,或其他有线字符,使得脚本执行失败(即使我已经用""把它包).有没有办法忽略那些角色?

Joh*_*nck 5

循环遍历shell脚本中的所有输入参数时,应始终使用"$@".不是$*,不是$@,不是"$*".只有"$@"这样才能完全正确处理所有输入字符串.

PS:总是用set -e和可能开始你的脚本set -o pipefail.然后,您的脚本将在第一个错误时停止,而不是使用未经测试的行为进行狂放.