What is the bash equivalent of python’s sys.argv method?

Asked

Viewed 97 times

2

In python, when I want to use a user-given string in the command line, I use the method sys.argv.

For example, let’s say I have an executable called 2name.py consisting of the following code:

import sys

lista_nomes = [sys.argv[k] for k in range(len(sys.argv))]

print("Seu segundo nome é {}".format(lista_nomes[2]))

On the linux terminal, when I type:

python 2name.py Édson Arantes do Nascimento

Returns:

Seu segundo nome é Arantes

I’d like to do this with bash files too, but I’m not getting it. In my search I found only how to use user input using command read (equivalent of input() python), but I want to use the input that is given directly on the command line, as well as the sys.argv. How do I do?

  • 2

    There is also the $@ (https://www.gnu.org/software/bash/html_node/Special-Parameters.html#index-_0024_0040) - see more details here. But in your case, use $2 it seems to me to go more directly to the point that you need. And just for the record, I didn’t need to create another list, just do it print("Seu segundo nome é {}".format(sys.argv[2])) (or, if using Python >= 3.6: print(f"Seu segundo nome é {sys.argv[2]}")). But if you want to create a copy of argv, can do lista_nomes = sys.argv[:] (fountain)

1 answer

5


Arguments passed in the command line for a Bash script are called positional parameters and are accessed using variables whose name is a number (!), thus: the first parameter is the $1, the second $2, the third $3, so on and so forth.

So if we have the script 2nomes.sh with the content:

#!/bin/bash

echo "O seu sobrenome é $2" 
echo "O seu nome é $1"

And we execute him like this:

./2nomes.sh Lima Barreto

The exit will be:

O seu sobrenome é Barreto
O seu nome é Lima

There are two other useful variables:

  1. $0 : the path of the script file, the way it was executed
  2. $# : number of arguments passed in the command line

In the above example, $0 is ". /2names.sh" and $# is 2.

  • 1

    and by the way $* would-be Lima Barreto

Browser other questions tagged

You are not signed in. Login or sign up in order to post.