Sch*_*ter 63 bash shell-script
我试图将 Bash 函数的所有参数连接到一个字符串中,每个参数之间用空格分隔。我还需要让字符串在整个字符串周围包含单引号。
这是我到目前为止...
$array=("$@")
str="\'"
for arg in "${array[@]}"; do
let $str=$str+$arg+" "
done
let $str=$str+"\'"
Run Code Online (Sandbox Code Playgroud)
显然这不起作用,但我想知道是否有办法实现这一目标?
Joh*_*024 99
我相信这可以满足您的需求。它将所有参数放在一个字符串中,用空格分隔,所有参数用单引号括起来:
str="'$*'"
Run Code Online (Sandbox Code Playgroud)
$*
生成由第一个字符分隔的所有脚本参数$IFS
,默认情况下,它是一个空格。
在双引号字符串中,不需要转义单引号。
让我们把上面的内容放在一个脚本文件中:
$ cat script.sh
#!/bin/sh
str="'$*'"
echo "$str"
Run Code Online (Sandbox Code Playgroud)
现在,使用示例参数运行脚本:
$ sh script.sh one two three four 5
'one two three four 5'
Run Code Online (Sandbox Code Playgroud)
这个脚本是POSIX。它可以使用,bash
但不需要bash
.
我们可以通过调整从空格更改为另一个字符IFS
:
$ cat script.sh
#!/bin/sh
old="$IFS"
IFS='/'
str="'$*'"
echo "$str"
IFS=$old
Run Code Online (Sandbox Code Playgroud)
例如:
$ sh script.sh one two three four
'one/two/three/four'
Run Code Online (Sandbox Code Playgroud)
这比你想象的要容易:
#!/bin/bash
array="${@}"
echo $array
Run Code Online (Sandbox Code Playgroud)
chmod +x 并运行它:
$ ./example.sh --foo bar -b az
--foo bar -b az
Run Code Online (Sandbox Code Playgroud)