Assigning a Variable a Filename in Bash

Assigning a Variable a Filename in Bash

I am writing a script to generate an executable (arm executable) in Linux by taking in user-specified .s file. So the user enters an input file, say "input.s" and an output file name, say "output.axf" and the script generates the desired output (executable - .axf). Now I want an additional option wherein, if the user does not give an output filename in the arguments, I want to create a default output file myself. The script is as follows:

#!/bin/bash
echo Enter the names of the input file and output file
read input_file output_file

if [ -z "$input_file" ] 
    then
        echo "No input supplied"

elif [ -z "$output_file" ]
    then
        $output_file=brot.axf

elif [ -z "$input_file" && -z "$output_file" ]
    then
        echo "No input/output file supplied"
fi

ifilename=$(basename "$input_file")
ifilename="${input_file%.*}"

armasm -g --cpu=8-A.64 "$input_file"
armlink "$ifilename.o" -o "$output_file"
fromelf --test -c $output_file > disassembly.txt

Now my problem is that every time I run the script and do not specify anything for $output_file, I get this error:

./script_test.sh: line 12: =brot.axf: command not found

Fatal error: L3901U: Missing argument for option 'o'.

However, when I do specify the input and output file names with extensions, it works as expected. How do I fix the error and assign a default name to the output file if the user doesn't assign one ?

2

2 Answers

Variable assignments don't take the $ notation in bash shell. You just need below without the $

output_file="brot.axf"

And later in the script if filename is a variable and trying to construct a name with .o appended, enclose the variable name within {} , so that the variable is expanded properly

armlink "${filename}.o" -o "$output_file"

Also by the looks of it you have a likely typo in the filename as variable ifilename. If you care trying to use it double-quote it as above.

0

You have to remove the $ in front of output_file on line 12.

output_file=brot.axf

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Maya Lin-Takahashi
Author

Maya Lin-Takahashi

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.