6

I have a simple bash file and want to execute a cd command:

#!/bin/bash
dir_path="~/Desktop/param_bind_b"
cd $dir_path

for some reason, when I try to run this script in terminal, I get this error:

student@ubuntu:~$ openptv_current_install.bash /home/student/Desktop/scripts/openptv_current_install.bash: line 3: cd: ~/Desktop/param_bind_b: No such file or directory

when I run the command cd ~/Desktop/param_bind_b "manually" it runs as expected.

what am I missing here?

1

2 Answers 2

8

Tilde (~) will not be expanded by shell when put inside quotes. Just remove the quotes :

#!/bin/bash
dir_path=~/Desktop/param_bind_b
cd "$dir_path"
3

An other solution is, place only the ~ outside the quotes or use $HOME instead. Additionally you should add || exit behind cd.

#!/bin/bash
dir_path=~"/Desktop/param_bind_b"
cd "$dir_path" || exit

Or

#!/bin/bash
dir_path="$HOME/Desktop/param_bind_b"
cd "$dir_path" || exit

so you can use other variables, E.G.

#!/bin/bash
desktop_dir="/Desktop"
dir_path=~"$desktop_dir/param_bind_b"
cd "$dir_path" || exit

or

#!/bin/bash
desktop_dir="/Desktop"
dir_path=~"$desktop_dir"/param_bind_b
cd "$dir_path" || exit

or

#!/bin/bash
desktop_dir="/Desktop"
dir_path="$HOME$desktop_dir"/param_bind_b
cd "$dir_path" || exit

In the future, check your scripts here. ;)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .