0

Problem:

I was hoping this would be something simple to do. I currently have my script changing my directory among other things and I was hoping that I could make the script change the line using echo to always display the current directory. A simple example of what I had in mind was (Please note the directories being used are arbitrary and not actually true):

TL;DR;

I would just like to have a line at the top of my script that tells me the current directory. Then while the rest of the script is running and if the directory changes I would like that top line to change with it to always display the current directory

CODE:

echo -e "Current Directory $PWD"
echo -en "\e[0K\r Finding folder"
cd /home/accounts
echo -en "\r\033[0K Inside folder"
cd /apps/foo/bar
echo -e "\e[0K\r Welcome to the app, enjoy!"

Expected Output:

At initial execution (Before the 1st cd command is executed)

Line 1: Current Directory: /var/www/project
Line 2: Finding Folder

After the 1st cd command is executed

Line 1: Current Directory: /home/accounts
Line 2: Inside Folder

After the 2nd cd command is executed

Line 1: Current Directory: /apps/foo/bar
Line 2: Welcome to the app, enjoy!
5
  • What do you mean by instance? What do you have to do to get these outputs? What did you get? and how did you get it? Commented Feb 14, 2020 at 18:41
  • This question is unclear: I have no idea what you are trying to do. What you have done. or what you are struggling with. Commented Feb 14, 2020 at 18:42
  • The verbiage might be incorrect so I apologize. I shall edit it to make more sense but long story short I would like to have at the top of my output say "Current Directory : foo/bar" and while the script continues to execute whenever the directory changes I was hoping to update that line with the new directory @ctrl-alt-delor Commented Feb 14, 2020 at 19:24
  • I as still confused. You have one script and it has the cd in it. Commented Feb 14, 2020 at 19:38
  • 1
    If you want to overwrite a line that got printed to the terminal, have a look at Overwrite last line on terminal. Commented Feb 15, 2020 at 8:26

2 Answers 2

2

For setting the prompt you use the variable PS1 not echo. In bash you can also use PROMPT_COMMAND.

E.G. using prompt codes

PS1='# \w '

or using commands

PS1="$(pwd)"

or variables

PS1="$PWD"
0
0

You can do this with an alias in your script:

alias echo='printf "Current Directory: $PWD\n" && echo'

Note that if you add this line to your script it will not change echo outside of your script. If you want to get the regular behavior of echo you can slash escape it:

\echo This will not produce the Current Directory line

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.