7

I want to store a user message in a bash program, and then display the message the next time the user runs the script.

One way I thought this might work is if I export the message to an environmental variable, but I cannot get it to work.

Here is what I have so far, but it is not working:

echo "Last message was: $KEEPTHISMESSAGE"
echo "Type the new message that you want to enter, followed by [ENTER]:"
read KEEPTHISMESSAGE
export KEEPTHISMESSAGE

What am I doing wrong? If there is a better way to do this, please let me know. Maybe keep a file that keeps a history of these message and gets the most recent?

eric
  • 1,453
  • 2
  • 20
  • 32

2 Answers2

7

You cannot use EXPORT this way. It only exports to processes started from within that invocation of the script. You must store the message in a file on the filesystem and load it in the next time your user executes the script. Very simply:

echo "Last message was: $(cat message.txt)"
echo "Type the new message that you want to enter, followed by [ENTER]:"
read KEEPTHISMESSAGE
echo $KEEPTHISMESSAGE > message.txt

You'll have to work out what happens the first time (when message.txt doesn't exist), and issues with relative/absolute paths to message.txt if you're running the script in a different directory.

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190
  • 3
    +1 This can be modified to use a hidden file (starts with a . ) Call it ~/.yourprog.history Read this file in your bash script by sourcing it, and overwrite the contents when your script ends. – Usman Saleem Sep 19 '11 at 23:55
  • 1
    echo $KEEPTHISMESSAGE > message.txt **overwrites or creates message.txt** ; Use >> for append – Paul Sep 19 '11 at 23:58
  • 1
    @Paul but appending is undesirable in his question, if he does that he should use `tail -1` instead of `cat` – Eric Fortis Sep 20 '11 at 00:01
  • @Jim and everyone else, thanks this was the solution. i also used >> for appending, and tail -1 instead of cat – eric Sep 20 '11 at 00:11
  • @Eric I was mostly concerned with resolving an issue "You'll have to work out what happens the first time when message.txt doesn't exist" in this answer. – Paul Sep 20 '11 at 02:11
  • 1
    '$ read -p "Type the new message that you want to enter, followed by [ENTER]:" KEEPTHISMESSAGE ' will do it in one step. – f4m8 Sep 20 '11 at 07:55
2

Scripts can only directly export variables to their sub-processes. They can't export to parent processes.

You can alter a parents environment by invoking your script like this:

$ . /path/to/your_script.sh

Here your script should have an export statement to export the variable and must not have an exit statement.

jman
  • 11,334
  • 5
  • 39
  • 61