0

I am trying to create a script whereby I have list of numerical test folders and want users to be able to cd into one of them after inputting the folder number.

The script correctly concatenates the input but on running the script it does not actually execute the cd command to the required directory?

It echo's to the screen but then just sits there as if awaiting a further prompt?

Can anyone advise what I am missing please? Script 'chgdir' is as below:

#!/bin/bash
#
# Script to move to test##dir (using input from user for dir number)
echo "Enter test directory number as ## and hit Return"

read dirnum

echo "cd /home/John/test$dirnum""dir"

However on running the script outputs the command to the screen but does not 'cd' and just remains in ~/bin?

cd /home/John/test01dir

John@John-PC ~/bin

P.S I am completely new to bash scripting as you can tell so any help really appreciated.

JFL
  • 1
  • 1

2 Answers2

2

All your script does is to echo the command that you formed. You need to actually execute the cd command as well as just echoing it.

cd /home/John/test ${dirnum}dir

The {} around the variable name allows the shell to distinguish the variable name from the extra characters appended after it.

That will change the directory inside the script. To have it apply afterwards, you will need to source the script (with dot "." or "source") to affect the shell you are running in.

Shadowfen
  • 459
  • 4
  • 11
  • That would change the directory in the shell script being run; it would not change the directory of the shell running the script. For that, you need `. script` (or, in Bash, `source script`). – Jonathan Leffler Jul 03 '16 at 05:25
0

Your script just prints the command. That's all the echo command does. It doesn't execute it, because you didn't tell it to.

You could execute the cd command by replacing the echo command with this:

cd "/home/John/test${dirnum}dir"

But if that's the last line of your script, it won't do anything useful. Doing a cd inside a script doesn't affect anything but the script itself.

If you want to cd from a script and have it take effect in the invoking shell, you can source the script rather than executing it:

. ./thescript

or you can have the script print the command you want to execute and eval its output:

eval "`./thescript`"

(To be clear, if you source the script using the . command, it needs to execute the cd command; if you val its output, the script needs to print the command.)

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
  • Thanks that was really useful. It was the 'cd' at the start as you say rather than the 'echo' and also sourcing the script as . ./chdir. – JFL Jul 03 '16 at 08:55