What is the dollar sign for before a variable?

Asked

Viewed 812 times

3

I would like to know the function of the dollar sign, and also if it is necessary that the variable is stuck ( no space ) in the equal sign ( = ) and the value of the variable ( GABRIEL ) and why?

example:

NOME="GABRIEL"
echo $NOME

2 answers

3

In Unix in general there is possibility to choose the "shell" that is intended to be used. Example: bash Dash zsh sh ksh csh ... Each has its syntactic and semantic definition.

In several Linux and Mac distributions, the default shell is bash: let’s assume we’re talking Bash. Here are some conventions:

Identifiers

  • By default identifiers are commands, files, folders, arguments : there is a need to "mark" variables in some way.

Definition of variables / assignment

  • id=exp assignment of a value to a variable
  • id = exp executes the "id" command by passing it as "=" and "Exp arguments"
  • id= date assigns the empty value to id and executes date

About the $ depending on the context, it can mean a lot of different things:

  • $id value of variable id
  • echo "o meu username é $USER" the variable value is expanded inside quotes strings (print "my username is jj")
  • $(comand) results in stdout of the command
  • $((3 + 4 + $a )) gives as a result the arithmetic calculation contained therein
  • a=(v0 v1 v2 v3 v4 v5) ; echo ${a[2]} gives the second value of an array (v2)

A small example:

$ A=ano
$ echo "o $A passado foi $(( $(date +%Y) - 1))"
o ano passado foi 2016

Finally, you remember that bash has:

  • variables, arrays, dictionaries
  • control structures (if, while, switch, for, ...)
  • functions (including recursive functions)

3


Serves to access values stored within variables. When to use prefix $ you will be wanting to access this value. See a very simple example.

#!/bin/sh

NAME="Zara Ali"
echo $NAME

I declared a variable NAME and stored the value "Zara Ali". To ACCESS this value "Zara Ali", I need the prefix $

  • @Jjoao Where? In my code there is no. You can edit the code of the user who asked the question.

  • @Jjoao now understood, I edited the code. Thank you so much for warning.

Browser other questions tagged

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