Reputation: 4171
I just want to do a simple greeting:
I tried:
echo "Welcome " + whoami
echo "Welcome " . whoami
and finally
echo "Welcome "; whoami
came close but it added a return character between the statements like this
Welcome
user
I want the output to be:
Welcome user
In general I want this to work:
#run
run(){
rc
show
pwd
a=whomai
b=pwd
c=timestamp
echo "Welcome $a, you are in $b, and the time is $c"
}
run
Upvotes: 0
Views: 886
Reputation: 295629
echo
emits a newline at the end of its output, and the usual ways to avoid this (with -n
) are not required to be supported by the POSIX standard (POSIX leaves echo behavior undefined with a wide array of inputs, making it undesirable for use with non-constant strings). Use printf
instead:
printf 'Welcome '; whoami
That said, if you want to assign output of a command to a variable, use command substitution:
a=$(whoami)
printf '%s\n' "Welcome, $a"
This can also be inlined:
printf '%s\n' "Welcome, $(whoami)"
Thus:
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"
}
Upvotes: 2