0

Is there a shell command to display the command prompt.

I will explain what i want through the illustration below.

When i execute script.sh, i should get the following output

$sh script.sh
$                   /* command prompt and then print hi */
hi

My script.sh is like this

#! /bin/bash

<command to display the shell command prompt>
echo "hi"
exit 0

what should the code that has to go in the place of angle brackets to get an output like above?

Thanks

2
  • What are you trying to do? 'echo $' would print a literal $ but is that what you're after?
    – Alex Holst
    Commented Jan 5, 2011 at 9:15
  • $ was just an example of propmt. I want the shell propmt to displayed as it was Commented Jan 5, 2011 at 9:25

1 Answer 1

2

There is no way to portably do as you ask, because the variable PS1 is only set when the shell is interactive, and should only by changed in dot-rc files if already set, as "is PS1 defined?" is the classic test for being in an interactive shell.

Choose your preferred prompt and use it. Classically, '$ ' for bourne-style shells, including bash (which default to 'bash-$ '), '> ' for tcsh, '% ' for zsh, and '# ' if root.

If you're trying to convey state for consistency, then just "Use '# ' if root, else '$ '."

5
  • Hi Phil, I did not understand you answer fully. Does your answer solve my problem. I do not want a mere $ or # to be displayed. I want to display the shell command once more as it is before the remaining lines in the script is executed Commented Jan 5, 2011 at 9:40
  • The shell command prompt is not defined in an interactive script, so you can't do this. You might set PS1, then source start-up files, hoping to pick up any overrides, but this is dangerous as things not suited to a script setup might be invoked, when "PS1 is set" is used as a short-cut for a bunch of expectations (eg, stdin is a tty).
    – Phil P
    Commented Jan 5, 2011 at 9:55
  • 1
    So: there is no command prompt in an interactive script, plus you can't find out what it would be if you weren't interactive. Thus you'll need to explain why you want to do whatever it is you're doing, for us to better help you achieve something realistic.
    – Phil P
    Commented Jan 5, 2011 at 9:56
  • +1, correct, you can't do it. PS1 isn't set because if your script could easily get the command prompt then you could easily emulate Bash for nefarious purposes, also known as a Trojan Horse virus/malware.
    – Chris S
    Commented Jan 5, 2011 at 13:40
  • Uh, no, that's not the reason PS1 isn't set. Most people will use the stock configuration supplied from the OS vendor and so it's easy enough to predict, and if malware has gotten that far, you're already screwed.
    – Phil P
    Commented Jan 9, 2011 at 0:30

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .