Sample Header Ad - 728x90

Commands cannot be located after sourcing a bash script

0 votes
2 answers
350 views
I have a short bash script cdline that takes two arguments PATHS and LINE and changes directory to the respective LINE in PATHS:
#!/bin/bash
#command for changing directory to that in the given line...
#or that of the file in the given line

PATHS=$1
LINE=$2
PATH="$(echo "${PATHS}" | sed -n ${LINE}p)"
PATH="$(/home/gohomology/Scripts/pc_macros/file_system/getdir "${PATH}")"
cd ${PATH}

return 1
This calls getdir which echoes the given path if its a directory, or the directory that includes the file otherwise. I know that when calling a bash script normally it creates a subshell, so trying to call the script normally wouldn't do anything. As far as I understand, the solution for this should be sourcing the script, which one can do adding . or source before calling the script. This indeed works for changing the directory, however, after doing so my terminal cannot find various commands such as ls or find, as demonstrated by the following result from my terminal emulator.
gohomology@gohomology:~/Desktop$ find . -name "example_file"
./example_dir/example_file

gohomology@gohomology:~/Desktop$ . cdline "$(!!)" 1
. cdline "$(find . -name "example_file")" 1

gohomology@gohomology:~/Desktop/example_dir$ ls
Command 'ls' is available in the following places
 * /bin/ls
 * /usr/bin/ls
The command could not be located because '/usr/bin:/bin' is not included in the PATH environment variable.
ls: command not found

gohomology@gohomology:~/Desktop/example_dir$ find . -name "example_file"
Command 'find' is available in the following places
 * /bin/find
 * /usr/bin/find
The command could not be located because '/bin:/usr/bin' is not included in the PATH environment variable.
find: command not found
The command cd still works after using cdline. I thought that the problem is that I'm stuck within a bash shell, which is why there's return 1 at the end of cdline, but the problem is still existent. I run bash 5.1.16 and gnome-terminal on Ubuntu 22.04.2.
Asked by gohomology (3 rep)
Jul 2, 2023, 12:16 PM
Last activity: Jul 2, 2023, 04:10 PM