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?

5 Answers 5

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.
2
  • 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...) Jun 7, 2016 at 6:16
  • Or create an alias.
    – Jenny D
    Jun 15, 2016 at 7: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.

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.

3
  • 1
    Why would you want sudo here?
    – user
    May 25, 2016 at 11:32
  • 1
    I would down vote if I had enough reputation because using sudo unnecessarily is just plain wrong. It seems that some people automatically use sudo for everything instead of learning when and why it's needed. May 25, 2016 at 13:21
  • Agreed with you guys. And I know When to use sudo. I didn't see the whole questions. May 25, 2016 at 13:50
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

0

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

2
  • 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, 2016 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 4, 2016 at 1:25

You must log in to answer this question.

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