8

I have a script:

#!/bin/bash
echo "$(dirname $(readlink -e $1))/$(basename $1)"

that sits here: /home/myuser/bin/abspath.sh which has execute permissions.

If I run echo $PATH I get the following: /usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin:/home/myuser/bin

I wish to be able to, from any directory, call abspath <some_path_here> and it call my script. I am using bash, what I am doing wrong?

Cheetah
  • 241
  • 3
  • 8

5 Answers5

30

You want to type abspath, but the program is named abspath.sh. The problem is not regarding whether it is in the PATH, but the fact that you are simply not using its name to call it.

You have two options:

  1. Type abspath.sh instead.
  2. Rename the program to abspath.
Michael Hampton
  • 244,070
  • 43
  • 506
  • 972
  • 1
    ... Or create a simlink: `cd $HOME/bin ; ln -s abspath.sh abspath`. This let you keep the correct extension for the script and having a tool named as you like. (You could in some futur, replace your shell script by a python script, for sample...) – F. Hauri - Give Up GitHub Jun 07 '16 at 06:16
  • Or create an alias. – Jenny D Jun 15 '16 at 07:57
6

This code is small enough that I would code it as a shell function:

abspath() {
    echo "$(dirname "$(readlink -e "$1")")/$(basename "$1")" 
} 

And yes you do want all those quotes.

glenn jackman
  • 4,630
  • 1
  • 17
  • 20
4

set an alias by adding your command in .bashrc file.

alias abspath='sh /home/myuser/bin/abspath.sh'

And don't forget to source the file.

2

I would rename your bash script to abspath then move it to the bin directory. You'll be ablet to call abspath from anywhere then

Harvey
  • 243
  • 1
  • 6
0

A 3rd option is to create an alias called abspath that points to your abspath.sh script.

tokamak
  • 109
  • 1
  • 5
    Not needed if fixed as the accepted solution explains, also quite convoluted and it actually hides a problem rather than addressing it. – dawud May 24 '16 at 17:04
  • Not worth arguing, but it goes without saying that if you solve it with one solution, you don't need to apply another solution. Yes this is a bandaid solution and referring directly to the shell script is a more ideal fix. – tokamak Jun 04 '16 at 01:25