脚本中带空格的文件名

Chr*_*s W 0 bash scripts

这是一个简单的脚本,用于将文件路径传递给lsorchmod但即使用引号括起来,带空格的文件名也不起作用。

我如何让它工作?

#!/bin/sh
# Script to fix permissions on supplied folder and file name

echo "Enter Folder name"
read folder
echo "Folder name is "$folder
echo "Enter File name - if name includes spaces enclose in single quote marks"
read filename 

echo "File name is "$filename
fullpath="/home/abc/"$folder"/"$filename

echo "Full path is "$fullpath

fixcommand="chmod a+rw -v "$fullpath

echo "Command to be executed is "$fixcommand

echo -n "Is that correct (y/n)? "
read answer
if echo "$answer" | grep -iq "^y" ;then
$fixcommand
else
    echo No action taken
fi 
Run Code Online (Sandbox Code Playgroud)

Yar*_*ron 8

在您提供的脚本中,变量实际上没有被引用

你应该更新你的脚本并用“”引用变量

例如:

fullpath="/home/abc/"$folder"/"$filename
Run Code Online (Sandbox Code Playgroud)

应该:

fullpath="/home/abc/$folder/$filename"
Run Code Online (Sandbox Code Playgroud)

感谢@glenn jackman - 他建议阅读忘记在 bash/POSIX shells 中引用变量的安全隐患

您可以在下面的脚本中找到shell-check 站点的完整反馈

Line 5:
read folder
^-- SC2162: read without -r will mangle backslashes.

Line 6:
echo "Folder name is "$folder
                      ^-- SC2086: Double quote to prevent globbing and word splitting.

Line 8:
read filename
^-- SC2162: read without -r will mangle backslashes.

Line 10:
echo "File name is "$filename
                    ^-- SC2086: Double quote to prevent globbing and word splitting.

Line 11:
fullpath="/home/abc/"$folder"/"$filename
                     ^-- SC2027: The surrounding quotes actually unquote this. Remove or escape them.

Line 13:
echo "Full path is "$fullpath
                    ^-- SC2086: Double quote to prevent globbing and word splitting.

Line 17:
echo "Command to be executed is "$fixcommand
                                 ^-- SC2086: Double quote to prevent globbing and word splitting.

Line 19:
echo -n "Is that correct (y/n)? "
     ^-- SC2039: In POSIX sh, echo flags are undefined.

Line 20:
read answer
^-- SC2162: read without -r will mangle backslashes.
Run Code Online (Sandbox Code Playgroud)

  • 另请参阅 [忘记在 bash/POSIX shell 中引用变量的安全隐患](https://unix.stackexchange.com/q/171346/4667) (2认同)