0

I'm working my way through the Wicked Cool Shell Scripts book. I've created a script, following the book's code, which can be found here. I'm trying to make an alias for this script so I can just call it from the terminal like a command. So, it can be used easily from any directory.

I've put the following code at the bottom of the script, run it and restarted the terminal, but it doesn't work.

alias formatdir='source ./shell_scripts/formatdir.sh'

I've searched online, but I haven't been able to get the programme to run just using an alias. Is this possible or am I misunderstanding what aliases do?

Thanks

  • Do you just want the alias formatdir to run that script? – Nasir Riley Jun 17 '19 at 19:19
  • 2
    You need to add the alias, not to the "formatdir.sh" script, but to one of the dotfiles that bash reads when it starts. Typically you would use $HOME/.bashrc – glenn jackman Jun 17 '19 at 19:20
2

The problem with your alias is that is uses a relative directory. So it will look for the script relative to the working directory. So, to get it to work you need to define the alias with an absolute path (why are you source by the way).

An alternative is to add the directory containing the scripts to the $PATH variable by placing the following in your ~/.bashrc (for bash):

export PATH=~/shell_scripts:$PATH

Doing so, you can call formatdir.sh from all new terminals. Also, you don't need to create an alias for every new script.

  • Thanks, though I'm not quite sure where to add this to the script? I've done a few combinations with no avail. Now, I'm adding this to the end of script. alias formatdir='source ./shell_scripts/formatdir.sh' – elliot Jun 17 '19 at 19:40
  • @elliot It does not go in the script (as glenn's comment above). Everything you want to do with the terminal preferably goes into .bashrc – Bernhard Jun 17 '19 at 19:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.