0

I make file "my.sh" and in the file I write code

if [ $# = 0 ]; then
   echo "filename: $0"
fi

and I execute my.sh file

$ my.sh -> I want output [filename: my.sh]

however, the result shows [filename: ./my.sh]

I finally want when I enter my.sh, the output shows [filename: my.sh] and when I enter ./my.sh, the output shows [filename: ./my.sh]

David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
apeach
  • 19
  • 3
  • `echo "filename: ${0##*/}"`? (using bash *parameter expansion with substring removal*) Also, you cannot execute `my.sh` alone without `./my.sh` unless `my.sh` is in a directory in your `PATH`. – David C. Rankin Dec 03 '19 at 07:08
  • And what happens when you run `/home/me/my.sh`? Do you strip `/home/me/`? Or do you only strip relative directories, like `../` and `./`? And how about paths like `/home/me/../me/../me/my.sh`? – jww Dec 03 '19 at 07:13
  • 2
    `[ $# = 0 ]` is incorrect and should 'technically' be `[ $# -eq 0 ]` so that an integer, rather than a string, comparison is made. – David C. Rankin Dec 03 '19 at 07:14
  • when i run "$ /home/fold/proj/my.sh", the result is filename: /home/fold/proj/my.sh – apeach Dec 03 '19 at 10:26
  • Additionally, I only run the file in the same directory. – apeach Dec 03 '19 at 10:50

1 Answers1

0

You could use basename:

#!/usr/bin/env bash
if [ $# = 0 ]; then
   echo $(basename $0)
fi

Also, take a note that [[ is generally safer to use.

funnydman
  • 9,083
  • 4
  • 40
  • 55