Argc and Argv in Bash [duplicate]
Asked Answered
Y

1

8

I written the following script which gets name of a file and then assemble and link the file. But it doesn't work. What is the problem with it?

EXPECTED_ARGS=2


if [ $# -ne $EXPECTED_ARGS ]
then
        echo "[+] Assembling with Nasm."
        nasm -f elf32 $1 -o $1.o

        echo "[+] Linking ..."
        ld $1.o -o $1

        echo "[+] Done!" 

else
        printf  "\nInvalid number of arguments, please check the inputs and try again\n"

fi;

When I run it without passing any args, it doesn't shows following error:

printf  "\nInvalid number of arguments, please check the inputs and try again\n"
Yoshikoyoshio answered 18/7, 2017 at 6:5 Comment(5)
First of all, you must reverse the logic of your if...then...else construct. Besides, contrary to the C convention, in bash $0 doesn't count as an argument, thus EXPECTED_ARGS must be 1 in your scriptPortly
I set it to 1 but nothing changed.Yoshikoyoshio
You must also reverse your if ... then ... else statement (i.e. print an error when the actual count of arguments is not equal to the expected count of arguments, and do the job otherwise)Portly
-ne is not equal... you swapped the conditions. if [ $# -eq $EXPECTED_ARGS ] ....Tyrocidine
From my perspective, looking for Bash's ARGC equivalent (with Google) (IE $# or ARGC=$(( $# ))), the question linked to as the original of the "duplicate" TOTALLY DOESN'T ANSWER that. Making me want to improve the answers here, yet I cannot.Joellajoelle
M
2

Define a variable: ARGC=$#

and your if statement will look like

if [ $ARGC -ne $MAX_ARGS ]; then

Legend:

  • -ne = not equal

  • -gt = greater than

  • -eq = equal to

Mannikin answered 7/9, 2017 at 8:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.