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

4

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Ah, I got careless there. Marked this question as duplicate. Thanks!
-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

1 Comment

In OP's example, $1 will correctly be asd.sh

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.