【问题标题】:How to accept user inpus from any console in shell script?如何在 shell 脚本中接受来自任何控制台的用户输入?
【发布时间】:2017-01-06 14:39:36
【问题描述】:

我有这个sn-p的代码

test.sh =>

#!/bin/bash
echo "i am running......."
while true  
        do
        echo "you typed  -----  $1" 
done

我只想要像我在哪里输入test hello,它应该打印you typed ----- hello。

示例: 控制台 1

vagrant@dummy:~$ sh test.sh
i am running.......

控制台 2

vagrant@dummy:~$ test hello
you typed  -----  hello

就像它应该像守护进程一样运行,我应该从任何地方调用它。有什么帮助吗?

【问题讨论】:

    标签: shell daemon


    【解决方案1】:

    你可以试试

    #!/bin/bash
    
    # read will return true as long as it reads the "delimiter" 
    while read -p "Please enter something: "
    do
        if [[ $REPLY == "stop" ]]
        then
            # break exits the "while" loop
            break
        else
            printf "%s\n" "you entered $REPLY"
        fi
    done
    

    【讨论】:

      【解决方案2】:

      您的代码看起来可以作为您想要的输出。

      为了能够从任何地方运行它 -

      • 将您的脚本从 test.sh 重命名为 test
      • 将脚本放置在 $PATH 变量中包含的位置。

      例如,

      $ echo $PATH
      /bin:/usr/bin:/etc:/usr/sbin 
      

      您可以将脚本放在上述目录之一中,也可以将 PATH 设置为包含更多位置,当您在 .profile 或 .bash_profile 中导出 PATH 时,每次登录时都会自动导出。

      将此添加到您的 ~/.profile -

      export PATH=$PATH:/dir/to/script
      

      将脚本放在 /dir/to/script 中。现在每次登录时,PATH 都会像 -

      $ echo $PATH
      /bin:/usr/bin:/etc:/usr/sbin:/script/to/dir
      

      现在,您可以在任何地方运行脚本 -

      $ test hello
      

      【讨论】:

        猜你喜欢
        • 2018-10-11
        • 2012-10-24
        • 1970-01-01
        • 1970-01-01
        • 2021-07-15
        • 2021-08-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-23
        相关资源
        最近更新 更多