有多种方法可以做您想要的。默认情况下,bash
使用空格作为默认分隔符,但是您可以使用IFS
(内部字段分隔符)轻松覆盖它,也可以使用其他技术(例如枚举)覆盖。以下是一些首先想到的示例。
变体#1
使用特殊的内部变量IFS
(内部字段分隔符)
#!/bin/bash
touch 'file a' 'file b'
# Set IFS to new line as a separator
IFS='
'
ls -la $( echo 'file a'; echo 'file b' )
变体#2
使用for
循环
#!/bin/bash
touch 'file a' 'file b'
for variable in 'file a' 'file b';do
ls -la "${variable}"
done
变体#3
使用for
预定义值中的循环
#!/bin/bash
MultiArgs='
arg 0 1
arg 0 2
arg 0 3
arg 0 N
'
# Using only new line as a separator
IFS='
'
for variable in ${MultiArgs};do
touch "${variable}"
ls -la "${variable}"
done
变体#4
使用~
(tilda)作为分隔符
#!/bin/bash
MultiArgs='arg 0 1~arg 0 2~arg0 3~ar g 0 N' # Arguments with spaces
IFS='~'
for file in ${MultiArgs};do
touch "${file}"
ls -la "${file}";
done
旧的反引号语法有什么不同吗?
不,它是相同的,但是反引号有一些限制$()
。
还是bash用户只是避免在文件名中使用空格或符号(例如动物)来简化一切?
不,可以在文件名中使用空格,只要使用正确的引号即可。
关于 $(cmdb-that-generates-parameters-for-cmda)
#!/bin/bash
# first command generate text for `sed` command that replacing . to ###
echo $( for i in {1..5}; do echo "${i} space .";done | sed 's/\./###/g' )
#############################################
# Another example: $() inside of another $()
for i in {1..5}; do touch "${i} x.file";done # Prepare some files with spaces in filenames
IFS='
'
echo "$( ls -la $(for i in ls *.file; do echo "$i"; done))"
如果您想在一行中传递所有参数来提供程序transcode
,则可以在~/.bashrc
文件末尾添加以下功能:
_tr() {
local debug
debug=1
[ $debug -eq 1 ] && {
echo "Number of Arguments: $#"
echo "Arguments: $@"
}
transcode "$@"
}
然后从命令行像下面这样调用该函数:
eval _tr $(echo "$out")
变量out
必须是这样的:out="'file a' 'file b'"
。
如果将手动键入文件名,则对_tr
函数的调用可能类似于:
eval _tr $(echo "'file a' 'file b'")
如果要使用某些外部脚本代替$()
外部脚本/程序,则必须返回引用如下的文件列表:
"'file a' 'file b'"