1

I'm new to bash scripting and I'm writing a script to automatically make a newly created .sh file executable. As such, I would want to check if .sh is preceded by the only argument provided in order to ensure a valid filename.

However, I'm getting a [: too many arguments error when I run ./createExecutableScript.sh asd.sh.

Initially, I thought it was because $1 was not wrapped in " that caused the error, and therefore added the "s in.

I also referred to this question (Linux Shell Script - String Comparison with wildcards) and added the *s outside of the "s.

#!/bin/bash

if [ "$#" -eq 1 ] && [ "$1" == *".sh" ]
then
    echo "Creating file with name: $1"
else
    echo "Invalid or missing filename!"
fi

jww
  • 97,681
  • 90
  • 411
  • 885
zeng
  • 23
  • 5
  • 2
    Post the content of your script – deosha Jun 23 '19 at 07:47
  • @deosha edited to include the script! – zeng Jun 23 '19 at 07:51
  • 1
    Shellcheck tells you what the problem is. Also see [How to use Shellcheck](http://github.com/koalaman/shellcheck), [How to debug a bash script?](http://unix.stackexchange.com/q/155551/56041) (U&L.SE), [How to debug a bash script?](http://stackoverflow.com/q/951336/608639) (SO), [How to debug bash script?](http://askubuntu.com/q/21136) (AskU), [Debugging Bash scripts](http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_02_03.html), etc. – jww Jun 23 '19 at 08:07
  • Thanks for sharing the resources, will look at them! @jww – zeng Jun 23 '19 at 19:23

2 Answers2

2

The answer in Linux Shell Script - String Comparison with wildcards is correct, you need to have double brackets like this:

#!/bin/bash

if [ "$#" -eq 1 ] && [[ "$1" == *".sh" ]]
then
    echo "Creating file with name: $1"
else
    echo "Invalid or missing filename!"
fi
Erez Ben Harush
  • 833
  • 9
  • 26
-1

So there is no variable as 1. You can do something like a=$1 and then put $a in the if statement. What you need is $($1) and not $1

deosha
  • 972
  • 5
  • 20