如何序列化bash命令?

时间:2015-11-28 17:49:25

标签: bash

我只是想做一个简单的问候:

我试过了:

echo "Welcome " + whoami

echo "Welcome " . whoami

最后

echo "Welcome "; whoami

接近但它在这样的语句之间添加了一个返回字符

Welcome 
user

我希望输出为:

Welcome user

一般来说,我希望这可以工作:

#run
run(){
    rc
    show
    pwd
    a=whomai
    b=pwd
    c=timestamp
    echo "Welcome $a, you are in $b, and the time is $c"
}

run

2 个答案:

答案 0 :(得分:2)

echo在其输出结尾处发出换行符,并且POSIX标准(POSIX leaves echo behavior undefined with a wide array of inputs不需要支持通常的避免此方法(使用-n),使其不适合与非常量字符串一起使用)。请改用printf

printf 'Welcome '; whoami

也就是说,如果要将命令的输出分配给变量,请使用command substitution

a=$(whoami)
printf '%s\n' "Welcome, $a"

这也可以内联:

printf '%s\n' "Welcome, $(whoami)"

因此:

run() {
    local a b c          # declare locals to avoid polluting namespace outside function

    a=${USER:-$(whoami)} # only call $(whoami) if $USER is unset
    b=$PWD               # more efficient than $(pwd), which runs a subshell
    c=$(date)            # for bash 4, this could be instead: printf -v c '%(%T)T' 0
                         # ...which would avoid calling external commands, and thus also
                         # ...be more efficient.
    printf '%s\n' "Welcome $a, you are in $b, and the time is $c"
}

答案 1 :(得分:2)

echo "Welcome $(whoami)"

应该这样做。