Linux bash脚本中带空格的basename?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7194192/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
basename with spaces in a bash script?
提问by cwd
I'm working on a bash script to create a new folder in /tmp/ using the name of a file, and then copy the file inside that folder.
我正在编写一个 bash 脚本,以使用文件名在 /tmp/ 中创建一个新文件夹,然后将该文件复制到该文件夹中。
#!/bin/bash
MYBASENAME="`basename `"
mkdir "/tmp/$MYBASENAME"
for ARG in "$@"
do
mv "$ARG" "/tmp/$MYBASENAME"
done
Behavior:
行为:
When I type in mymove "/home/me/downloads/my new file.zip"
it shows this:
当我输入时,mymove "/home/me/downloads/my new file.zip"
它显示:
mkdir /tmp/my
new
file.zip
mv: rename /home/me/downloads/my new file.zip to /tmp/my\nnew\nfile.zip:
I have lots of quotes around everything, so I don't understand why this is not working as expected.
我对所有内容都有很多引用,所以我不明白为什么这不能按预期工作。
Also, I have the form loop in there in case there are multiple files. I want them all to be copied to the same folder, based on the first argument's basename.
另外,我在那里有表单循环,以防有多个文件。我希望根据第一个参数的基本名称将它们全部复制到同一个文件夹中。
采纳答案by Jens
In the case where the assignment is a single command substitution you do not need to quote the command substitution. The shell does not perform word splitting for variable assignments.
在分配是单个命令替换的情况下,您不需要引用命令替换。shell 不对变量赋值进行分词。
MYBASENAME=$(basename "")
is all it takes. You should get into the habit of using $()
instead of backticks because $()
nests more easily (it's POSIX, btw., and all modern shells support it.)
这就是全部。你应该养成使用$()
而不是反引号的习惯,因为$()
嵌套更容易(它是 POSIX,顺便说一句,所有现代 shell 都支持它。)
PS: You should try to notwrite bashscripts. Try writing shellscripts. The difference being the absence of bashisms, zshisms, etc. Just like for C, portability is a desired feature of scripts, especially if it can be attained easily. Your script does not use any bashisms, so I'd write #!/bin/sh
instead. For the nit pickers: Yes, I know, old SunOS and Solaris /bin/sh
do not understand $()
but the /usr/xpg4/bin/sh
is a POSIX shell.
PS:你应该尽量不要写bash脚本。尝试编写shell脚本。不同之处在于没有 bashisms、zshisms 等。就像对于 C 一样,可移植性是脚本的一个理想特性,特别是如果它可以轻松实现。你的脚本没有使用任何 bashisms,所以我会写#!/bin/sh
。对于 nit 选择者:是的,我知道,旧的 SunOS 和 Solaris/bin/sh
不理解,$()
但它/usr/xpg4/bin/sh
是 POSIX shell。
回答by Ulrich Dangel
The problem is that $1
in
问题是$1
在
MYBASENAME="`basename `"
is not quoted. Use this instead:
没有引用。改用这个:
MYBASENAME="$(basename "")"
回答by phoxis
MYBASENAME="`basename `"
should be
应该
MYBASENAME="`basename ""`"
Wrap the $1
with double quotes "$1"
$1
用双引号包裹"$1"
回答by Carl Norum
You're missing one set of quotes!
您缺少一组引号!
MYBASENAME="`basename \"\"`"
That'll fix your problem.
那会解决你的问题。