I need to check with my Bash script, if there is a Shebang in the frist line of a .txt file. This is my code so far:
#Lists all valid parameters#
listParameter(){
echo "Invalid parameter. Please use one of the following keywords:"
echo -e "(txxxxx | stat | all | plag)\n"
}
if [ -z $1 ]
then
listParameter
exit 1
else
if [ ${1:0:1} == "t" ]
then
if [ ! -f "$1" ]
then
echo -e "File missing. Please import $1 to this path.\n"
exit 1
else
FILE = $1
FIRSTLINE="head -n 1 $FILE"
if [FIRSTLINE == "#!"]
then
echo "Lorem Ipsum"
else
echo "Lorem Ipsum"
fi
fi
I need to make different "tests" by different command line parameters. So first of all I checked if §1 is starting with a t. Than I know its txxxxx parameter. txxxxx is the name of a txt file. Than I check if this file exist. If yes I want to check, if the first row of the file starts with a "#!". But this is not working and i dont know why. The txxxxx file and the bash script are in the same folder. So all in all, I just dont know how I can open and analyse a certain .txt file... :/
Hope someone can help me.
CodePudding user response:
It looks like you are not executing the "head -n 1..." command, but treating it as a string. To run it use:
FIRSTLINE=$(head -n 1 "$FILE")
Then you probably want to check if first line starts with shebang, not necessarily is shebang.
CodePudding user response:
You can use the builtin read
. You don't need to call an external command like head
and invoke a subshell.
#!/bin/bash
file=$1
if IFS= read -r firstline < "$file" && [[ $firstline = '#!'* ]]
then
printf 'The file %s contains shebang\n' "$file"
fi
As an aside, you shouldn't use capitalized variable names for your own variables in shell programming, by convention. Environment variables and internal shell variables are capitalized. All other variable names should be lower case. This convention avoids accidentally overriding environmental and internal variables.
CodePudding user response:
Whitespace matters. The line if [FIRSTLINE == "#!"]
is incorrect, as it attempts to executes a command names [FIRSTLINE
, which probably does not exist. You want:
if [ "$FIRSTLINE" = "#!" ]
Also, instead of if [ -z $1 ]
, you ought to use if [ -z "$1" ]