Reputation: 12651
I need to get the value of the PS1
variable inside a bash script.
I know that running the script with a dot before makes bash pass env variables to the script, but I need to get PS1
regardless of how it is invoked, since I don't trust who will run the script.
How do I get it?
Update:
the variable has been exported in /etc/profile
, but I cannot get it:
[ Test ] root@myhost:~# export | grep PS1
declare -x PS1="[ Test ] \\u@\\h:\\w\\\$ "
[ Test ] root@myhost:~# cat test.sh
echo $PS1
[ Test ] root@myhost:~# bash test.sh
I get no output from the last command.
Upvotes: 2
Views: 3768
Reputation: 39
5 years later....because i used the following solution after finding this question.
If you want you can use the -i flag in the header and it seems to keep the environment during the script without having to run it in a special manner. I.e.
#!/bin/bash -i
echo "$PS1"
I don't know if this has any other weird behaviors, but it worked for what I needed.
Upvotes: 3
Reputation: 562
Start your test script with 'bash -i'; this makes it behave like a login shell and (amongst other things) sets PS1.
If your script will be run as an executable (.e.g ./test.sh) then you can also provide -i on the initial line, like this:
#!/bin/bash -i
Update: This only works if your script is executed directly, e.g.
$ ./test.sh
and not as:
$ bash test.sh
as that runs it in a non-interactive shell again. If you want to use bash from the command line, then do it like this:
$ bash -i test.sh
Upvotes: 9
Reputation:
This variable is somehow treated in a special way in bash (but eg in AIX or HPUX sh
that i know you can access it even while non-interactive). It's being used only in interactive shell, so there's no possibility to get access to its value in non-interactive invocation.
Sorry, it's no answer, but that's how it is...
Upvotes: 2