0

I know this question has been asked several times, but yet I failed to find a suitable solution for me. Consider me somewhat new to it.
I want to change the directory using a variable 'var' in the script file 'test.sh' instead of using cd /dir/dir1/dir2.

Question:
file example: test.sh

#!/bin/bash
var=/dir/dir1/dir2
echo "$var"   -> works(displays the value of var)
cd var     or     cd $var    -> none works, either stay in the same directory or shows error directory doesn't exsist

The directory I wanted to use:
/home/username/Downloads
/boot/extlinux

I have already checked various forums or solutions, but none provided the result. Please help me here.

Cyrus
  • 84,225
  • 14
  • 89
  • 153
  • How are you concluding it doesn't work? Are you expecting the directory to be changed in the controlling terminal after the script completes? – kaylum May 31 '20 at 08:22
  • 1
    Use `cd "$var"` and see [Why doesn't “cd” work in a shell script?](https://stackoverflow.com/q/255414/3776858) – Cyrus May 31 '20 at 08:34
  • if *'cd var'* shows **no** error then it successful changed into existing folder *'var'* but if *'cd $var'* **shows** error then folder *'/dir/dir1/dir2'* does not exist (wrong path or missing double quotes). nevertheless you can add `|| exit 1` to make sure your (whatever) next script cmd lines are executed inside *'dir2'* (and add `echo $PWD` to double check for debugging purposes) – alecxs May 31 '20 at 09:52

0 Answers0