LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Use of $ in shell script (https://www.linuxquestions.org/questions/linux-newbie-8/use-of-%24-in-shell-script-4175463942/)

kingissingh@gmail.com 05-29-2013 08:07 AM

Use of $ in shell script
 
I have the following script that counts the number of A/a entered by user. But I do not completely understand the line 4 and 6. I will be thankful if some one explains what is the special use of $ here.

1. #!/bin/bash -
2. echo "Enter A or a"
3. read text
4. A="${text//[^a|A]}"
5. echo "$A"
6. echo "${#A}"

O/P
------------
$ ./test_move
Enter A or a
AAALL
AAA
3

Ygrex 05-29-2013 08:23 AM

http://www.gnu.org/software/bash/man...Expansion.html

pattern substitution (4) and string length (6)

Madhu Desai 05-29-2013 10:13 AM

Pattern search and replace:

There are 4 type of pattern search and replaces,
  1. ${PARAMETER/PATTERN/STRING} = In the given PARAMETER, the first PATTERN is matched and is replaced by STRING
  2. ${PARAMETER//PATTERN/STRING} = In the given PARAMETER, all the PATTERN(s) are matched and are replaced by STRING
  3. ${PARAMETER/PATTERN} = In the given PARAMETER, the first PATTERN is matched and is replaced by nullstring, i.e. nothing
  4. ${PARAMETER//PATTERN} = In the given PARAMETER, all the PATTERNS(s) are matched and are replaced by nullstring, i.e. nothing

In your case its type 4:

let's say you input text="A a B X a AAaa"

here PARAMATER is "A a B X a AAaa" and the PATTERN that is provided is [^a|A] i.e, not a or not A

"${text//[^a|A]}" means replace all which are not either a or A in text with nullstring. so the space and the letters other than a or A will be removed. the result will be AaaAAaa

"${#A}" means length of the string in variable A. result will be 7

I hope i have made it clear. :)

more: Parameter expansion

kingissingh@gmail.com 05-30-2013 03:56 AM

Thank you
 
That was a good explanation from mddesai, also thank for the links posted by mddesai and Ygrex.
The links help me get more information that I was looking for, appreciate it.


All times are GMT -5. The time now is 02:57 AM.