热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

在bash脚本中使用空格的basename?-basenamewithspacesinabashscript?

Imworkingonabashscripttocreateanewfolderintmpusingthenameofafile,andthencopy

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 $1`"
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.

另外,如果有多个文件,我在那里有表单循环。我希望根据第一个参数的basename将它们全部复制到同一个文件夹中。

4 个解决方案

#1


13  

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 "$1")

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 not write bash scripts. Try writing shell scripts. 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。对于挑选者:是的,我知道,旧的SunOS和Solaris / bin / sh不理解$()但是/ usr / xpg4 / bin / sh是POSIX shell。

#2


4  

The problem is that $1 in

问题是1美元

MYBASENAME="`basename $1`" 

is not quoted. Use this instead:

没有引用。改为使用它:

MYBASENAME="$(basename "$1")"

#3


2  

You're missing one set of quotes!

你错过了一套报价!

MYBASENAME="`basename \"$1\"`"

That'll fix your problem.

这将解决你的问题。

#4


0  

MYBASENAME="`basename $1`"

should be

应该

MYBASENAME="`basename "$1"`"

Wrap the $1 with double quotes "$1"

用双引号“$ 1”包裹1美元


推荐阅读
author-avatar
白骨精哥哥_350
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有