The following question is from Pro Bash Scripting 2nd Edition: Exercises By defa
ID: 3590183 • Letter: T
Question
The following question is from Pro Bash Scripting 2nd Edition:
Exercises By default, where can a variable assigned in a script be accessed? Select all that apply: 1. In the current script In functions defined in the current script In the script that called the current script In scripts called by the current script . In subshells of the current script 2. I advise against uing single-letter variables names but give a couple of places where they are reasonable. Can you think of any other legitimate uses for them? 3. Given var=192.168.0.123, write a script that uses parameter expansion to extract the second number, 168.Explanation / Answer
Answer1:
(Assuming Unexported (i.e. local) variable declaration
In the current script: True
In functions defined in the current script: True
In the script that called the current script: False [Unexported variables cannot be accessed outside the current script]
In scripts called by the current script: True
In subshell of the current script: False
Just to increase your knowlege please read below:
bash, variables can have three scopes:
# Global variable declaration
export environment=one
# Function local variable declaration
function f
{
typeset local=three
}
# Unexported (i.e. local) variable declaration
local1=two
Note: typeset Variables declared in shell functions are only visible inside the functions.
Answer2:
Variable names must be having meaningful names. The sole purpose behing such naming is to increase readablility of code. Readability Simply means if I have written the code and you are asked to review my code then you should be able to understand the use of a variable or function by its name itself.
Variable names consisting only single character is usually used where the scope of the variable is limited to certain block of code.
Example: variables used in initialization of Loops, Temporary variables(which are limited for seeting up some other variable).
One major use of sigle character variable naming is in "Obfuscation". Obfuscation is a practce which is used to make code unreadable and hard to be read by the hackers or attackers. So it increases Security.
Answer3:
var=192.168.111.12
echo ${var:4:3}
#Explaination: Here 4 is the place value from where you want the substring and 3 is the number of characters you want to get.
#If you get any doubt please comment. Happy Chegging :)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.