6

Silly question, but since I'm such a newbie at Linux OS, I'm having trouble to make this simple script to echo the result of PS1.

If I type echo $PS1 in bash, it shows me the result, but not in the script. It returns blank.

Example:

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

Any tips for a begginer?

Thanks in advance.

glglgl
  • 89,107
  • 13
  • 149
  • 217
Rafael
  • 113
  • 2
  • 7
  • 3
    `ps1="$PS1"` is more efficient and more correct. `echo` isn't needed. *Always* quote your parameter expansions. – chepner Feb 07 '18 at 13:10
  • Try to do it with `eval` $PS1 and `sed`, as nicely answered here: https://stackoverflow.com/questions/22322879/how-to-print-current-bash-prompt/44090232#44090232 – Noam Manos Nov 27 '18 at 07:45

4 Answers4

8

Other answers are correct. If you add the -i flag to your shebang, that signals bash that it's supposed to be an interactive shell, so it will read your ~/.bashrc -- see https://www.gnu.org/software/bash/manual/bashref.html#Invoking-Bash

#!/bin/bash -i
ps1="$PS1"
echo "$ps1"
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
5

PS1 is a variable which is not "exported", so it is only visible within the shell, but not from any subprocess such as the script's.

glglgl
  • 89,107
  • 13
  • 149
  • 217
4

PS1 is typically not exported, since it is usually defined in .bashrc, which is sourced by every shell that would need PS1. As such, it isn't inherited by the non-interactive shell that executes your script.

chepner
  • 497,756
  • 71
  • 530
  • 681
0

try this script from the documentation ..this might help you :

PS1 – The value of this parameter is used as the primary prompt string. The default value is \u@\h \W\$ .

$ echo $PS1 Sample output: [\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

Examples:

PS1="\d \h $ " Sample output: Sat Jun 02 server $

PS1="[\d \t \u@\h:\w ] $ " Sample output: [Sat Jun 02 14:24:12 vivek@server:~ ] $