$user 或 $whoami 不在 bash shell 脚本中工作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25107462/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 11:01:01  来源:igfitidea点击:

$user or $whoami not working in a bash shell script

bashunix

提问by Mistu4u

I am learning basic unix shell scripting now. I was trying a code from hereto write my username but it is not working.

我现在正在学习基本的 unix shell 脚本。我正在尝试使用此处的代码来编写我的用户名,但它不起作用。

The code is:

代码是:

#
# Script to print user information who is currently logged in , current date & time
#
clear
echo "Hello $USER"
echo "Today is \c ";date
echo "Number of user login : \c" ; who | wc -l
echo "Calendar"
cal
exit 0

I tried $whoamiinstead of $user, but still it is not showing my username. What can be the issue here? I am using vim editor in Ubuntu.

我尝试了$whoami而不是$user,但它仍然没有显示我的用户名。这里有什么问题?我在 Ubuntu 中使用 vim 编辑器。

回答by Shiplu Mokaddim

  1. If $USERis not working try, $LOGNAME. If you have already learned about command substitution then you can use $(whoami)or $(id -n -u). Ref
  2. \cin echowont work unless you specify with -e(stands for enable interpretation of backslash escapes).

    echo -e "Today is \c ";date
    

    It seems you want to prevent the trailing new line character introduced by echo. Another way to achieve this is to just add -n. Then you don't need -eand \c.

    echo -n "Today is "; date
    
  1. 如果$USER不起作用,请尝试$LOGNAME。如果您已经了解了命令替换,那么您可以使用$(whoami)$(id -n -u)参考
  2. \cinecho除非您指定 with -e(代表启用反斜杠转义的解释),否则将无法工作。

    echo -e "Today is \c ";date
    

    似乎您想防止由echo. 实现此目的的另一种方法是添加-n. 那你就不需要-eand 了\c

    echo -n "Today is "; date
    

回答by konsolebox

I tried `$whoami`

我试过 `$whoami`

What you probably mean to do is `whoami`or $(whoami).

您可能想要做的是`whoami`$(whoami)

See Command Substitution.

请参阅命令替换