【问题标题】:echo $PS1 in script在脚本中回显 $PS1
【发布时间】:2018-02-07 13:06:31
【问题描述】:

愚蠢的问题,但由于我是 Linux 操作系统的新手,所以我很难制作这个简单的脚本来回应 PS1 的结果。

如果我在 bash 中输入 echo $PS1,它会显示结果,但不会显示在脚本中。它返回空白。

例子:

#!/bin/bash
ps1=$(echo $PS1) 
echo $ps1

对初学者有什么建议吗?

提前致谢。

【问题讨论】:

  • ps1="$PS1" 更高效、更正确。 echo 不需要。 总是引用你的参数扩展。
  • 尝试使用eval $PS1 和sed 来做这件事,这里得到了很好的回答:stackoverflow.com/questions/22322879/…

标签: bash shell ps1


【解决方案1】:

其他答案是正确的。如果你将-i 标志添加到你的shebang,这表明bash 它应该是一个交互式shell,所以它会读取你的~/.bashrc——见https://www.gnu.org/software/bash/manual/bashref.html#Invoking-Bash

#!/bin/bash -i
ps1="$PS1"
echo "$ps1"

【讨论】:

  • 正是我今天需要知道的。
【解决方案2】:

PS1 通常不会导出,因为它通常在.bashrc 中定义,它由需要PS1 的每个shell 提供。因此,执行脚本的非交互式 shell 不会继承它。

【讨论】:

    【解决方案3】:

    PS1 是一个未“导出”的变量,因此它仅在 shell 中可见,而在脚本等任何子进程中不可见。

    【讨论】:

      【解决方案4】:

      从文档中尝试这个脚本..这可能会帮助你:

      PS1 – 此参数的值用作主要提示字符串。默认值为 \u@\h \W\$ 。

      $ echo $PS1 示例输出:[\u@\h \W]$

      \a : an ASCII bell character (07)
      \d : the date in “Weekday Month Date” format (e.g., “Tue May 26”)
      \e : an ASCII escape character (033)
      \h : the hostname up to the first ‘.’
      \H : the hostname
      \j : the number of jobs currently managed by the shell
      \l : the basename of the shell’s terminal device name
      \n : newline
      \r : carriage return
      \u : the username of the current user
      \v : the version of bash (e.g., 2.00)
      \V : the release of bash, version + patch level (e.g., 2.00.0)
      \w : the current working directory, with $HOME abbreviated with a tilde
      \W : the basename of the current working directory, with $HOME abbreviated with a tilde
      

      例子:

      PS1="\d \h $" 示例输出:Sat Jun 02 server $

      PS1="[\d \t \u@\h:\w ] $ " 示例输出:[Sat Jun 02 14:24:12 vivek@server:~ ] $

      【讨论】:

      • 嗨 Piyush,不回答这个问题。请尽量保持更多的话题^_^
      猜你喜欢
      • 2011-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多