20150518-2 选题

This commit is contained in:
DeadFire 2015-05-18 16:16:32 +08:00
parent e49ed47aac
commit e79f29cffc
2 changed files with 592 additions and 0 deletions

View File

@ -0,0 +1,193 @@
10 Amazing and Mysterious Uses of (!) Symbol or Operator in Linux Commands
================================================================================
The `'!'` symbol or operator in Linux can be used as Logical Negation operator as well as to fetch commands from history with tweaks or to run previously run command with modification. All the commands below have been checked explicitly in bash Shell. Though I have not checked but a major of these wont run in other shell. Here we go into the amazing and mysterious uses of `'!'` symbol or operator in Linux commands.
### 1. Run a command from history by command number. ###
You might not be aware of the fact that you can run a command from your history command (already/earlier executed commands). To get started first find the command number by running history command.
$ history
![Find Last Executed Commands with History Command](http://www.tecmint.com/wp-content/uploads/2015/05/history-Command.gif)
Now run a command from history just by the number at which it appears, in the output of history. Say run a command that appears at number 1551 in the output of history command.
$ !1551
![Run Last Executed Commands by Number ID](http://www.tecmint.com/wp-content/uploads/2015/05/Run-Commands-By-number.gif)
And, it runs the command ([top command][1] in the above case), that was listed at number 1551. This way to retrieving already executed command is very helpful specially in case of those commands which are long. You just need to call it using **![Number at which it appears in the output of history command]**.
### 2. Run previously executed command as 2nd last command, 7th last command,etc. ###
You may run those commands which you have run previously by their running sequence being the last run command will be represented as -1, second last as -2, seventh last as -7,….
First run history command to get a list of last executed command. It is necessary to run history command, so that you can be sure that there is no command like `rm command > file` and others just to make sure you do not run any dangerous command accidentally. And then check Sixth last command, Eight last command and Tenth last command.
$ history
$ !-6
$ !-8
$ !-10
![Run Last Executed Commands By Numbers](http://www.tecmint.com/wp-content/uploads/2015/05/3.gif)
Run Last Executed Commands By Numbers
### 3. Pass arguments of last command that we run to the new command without retyping ###
I need to list the content of directory /home/$USER/Binary/firefox so I fired.
$ ls /home/$USER/Binary/firefox
Then I realized that I should have fired ls -l to see which file is executable there? So should I type the whole command again! No I dont need. I just need to carry the last argument to this new command as:
$ ls -l !$
Here `!$` will carry arguments passed in last command to this new command.
![Pass Arguments of Last Executed Command to New](http://www.tecmint.com/wp-content/uploads/2015/05/4.gif)
Pass Arguments of Last Executed Command to New
### 4. How to handle two or more arguments using (!) ###
Lets say I created a text file 1.txt on the Desktop.
$ touch /home/avi/Desktop/1.txt
and then copy it to /home/avi/Downloads using complete path on either side with cp command.
$ cp /home/avi/Desktop/1.txt /home/avi/downloads
Now we have passed two arguments with cp command. First is /home/avi/Desktop/1.txt and second is /home/avi/Downloads, lets handle them differently, just execute `echo [arguments]` to print both arguments differently.
$ echo “1st Argument is : !^”
$ echo “2nd Argument is : !cp:2”
Note 1st argument can be printed as `“!^”` and rest of the arguments can be printed by executing `“![Name_of_Command]:[Number_of_argument]”`.
In the above example the first command was cp and 2nd argument was needed to print. Hence `“!cp:2”`, if any command say xyz is run with 5 arguments and you need to get 4th argument, you may use `“!xyz:4”`, and use it as you like. All the arguments can be accessed by `“!*”`.
![Handle Two or More Arguments](http://www.tecmint.com/wp-content/uploads/2015/05/5.gif)
Handle Two or More Arguments
### 5. Execute last command on the basis of keywords ###
We can execute the last executed command on the basis of keywords. We can understand it as follows:
$ ls /home > /dev/null [Command 1]
$ ls -l /home/avi/Desktop > /dev/null [Command 2]
$ ls -la /home/avi/Downloads > /dev/null [Command 3]
$ ls -lA /usr/bin > /dev/null [Command 4]
Here we have used same command (ls) but with different switches and for different folders. Moreover we have sent to output of each command to /dev/null as we are not going to deal with the output of the command also the console remains clean.
Now Execute last run command on the basis of keywords.
$ ! ls [Command 1]
$ ! ls -l [Command 2]
$ ! ls -la [Command 3]
$ ! ls -lA [Command 4]
Check the output and you will be astonished that you are running already executed commands just by `ls` keywords.
![Run Commands Based on Keywords](http://www.tecmint.com/wp-content/uploads/2015/05/6.gif)
Run Commands Based on Keywords
### 6. The power of !! Operator ###
You can run/alter your last run command using `(!!)`. It will call the last run command with alter/tweak in the current command. Lets show you the scenario
Last day I run a one-liner script to get my private IP so I run,
$ ip addr show | grep inet | grep -v 'inet6'| grep -v '127.0.0.1' | awk '{print $2}' | cut -f1 -d/
Then suddenly I figured out that I need to redirect the output of the above script to a file ip.txt, so what should I do? Should I retype the whole command again and redirect the output to a file? Well an easy solution is to use `UP` navigation key and add `'> ip.txt'` to redirect the output to a file as.
$ ip addr show | grep inet | grep -v 'inet6'| grep -v '127.0.0.1' | awk '{print $2}' | cut -f1 -d/ > ip.txt
Thanks to the life Savior `UP` navigation key here. Now consider the below condition, the next time I run below one-liner script.
$ ifconfig | grep "inet addr:" | awk '{print $2}' | grep -v '127.0.0.1' | cut -f2 -d:
As soon as I run script, the bash prompt returned an error with the message `“bash: ifconfig: command not found”`, It was not difficult for me to guess I run this command as user where it should be run as root.
So whats the solution? It is difficult to login to root and then type the whole command again! Also (UP Navigation Key) in last example didnt came to rescue here. So? We need to call `“!!”` without quotes, which will call the last command for that user.
$ su -c “!!” root
Here su is switch user which is root, `-c` is to run the specific command as the user and the most important part `!!` will be replaced by command and last run command will be substituted here. Yeah! You need to provide root password.
![The Power of !! Key](http://www.tecmint.com/wp-content/uploads/2015/05/7.gif)
The Power of !! Key
I make use of `!!` mostly in following scenarios,
1. When I run apt-get command as normal user, I usually get an error saying you dont have permission to execute.
$ apt-get upgrade && apt-get dist-upgrade
Opps error…dont worry execute below command to get it successful..
$ su -c !!
Same way I do for,
$ service apache2 start
or
$ /etc/init.d/apache2 start
or
$ systemctl start apache2
OOPS User not authorized to carry such task, so I run..
$ su -c 'service apache2 start'
or
$ su -c '/etc/init.d/apache2 start'
or
$ su -c 'systemctl start apache2'
### 7. Run a command that affects all the file except ![FILE_NAME] ###
The `!` (Logical NOT) can be used to run the command on all the files/extension except that is behind `'!'`.
A. Remove all the files from a directory except the one the name of which is 2.txt.
$ rm !(2.txt)
B. Remove all the file type from the folder except the one the extension of which is pdf.
$ $ rm !(*.pdf)
### 8. Check if a directory (say /home/avi/Tecmint)exist or not? Printf if the said directory exist or not. ###
Here we will use `'! -d'` to validate if the directory exist or not followed by Logical AND Operator `(&&)` to print that directory does not exist and Logical OR Operator `(||)` to print the directory is present.
Logic is, when the output of `[ ! -d /home/avi/Tecmint ]` is 0, it will execute what lies beyond Logical AND else it will go to Logical OR `(||)` and execute what lies beyond Logical OR.
$ [ ! -d /home/avi/Tecmint ] && printf '\nno such /home/avi/Tecmint directory exist\n' || printf '\n/home/avi/Tecmint directory exist\n'
### 9. Check if a directory exist or not? If not exit the command. ###
Similar to the above condition, but here if the desired directory doesnt exist it will exit the command.
$ [ ! -d /home/avi/Tecmint ] && exit
### 10. Create a directory (say test) in your home directory if it does not exist. ###
A general implementation in Scripting Language where if the desired directory does not exist, it will create one.
[ ! -d /home/avi/Tecmint ] && mkdir /home/avi/Tecmint
Thats all for now. If you know or come across any other use of `'!'` which is worth knowing, you may like to provide us with your suggestion in the feedback. Keep connected!
--------------------------------------------------------------------------------
via: http://www.tecmint.com/mysterious-uses-of-symbol-or-operator-in-linux-commands/
作者:[Avishek Kumar][a]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创翻译,[Linux中国](https://linux.cn/) 荣誉推出
[a]:http://www.tecmint.com/author/avishek/
[1]:http://www.tecmint.com/12-top-command-examples-in-linux/

View File

@ -0,0 +1,399 @@
70 Expected Shell Scripting Interview Questions & Answers
================================================================================
We have selected expected 70 shell scripting question and answers for your interview preparation. Its really vital for all system admin to know scripting or atleast the basics which in turn helps to automate many tasks in your work environment. In the past few years we have seen that all linux job specification requires scripting skills.
### 1) How to pass argument to a script ? ###
./script argument
**Example** : Script will show filename
./show.sh file1.txt
cat show.sh
#!/bin/bash
cat $1
### 2) How to use argument in a script ? ###
First argument: $1,
Second argument : $2
Example : Script will copy file (arg1) to destination (arg2)
./copy.sh file1.txt /tmp/
cat copy.sh
#!/bin/bash
cp $1 $2
### 3) How to calculate number of passed arguments ? ###
$#
### 4) How to get script name inside a script ? ###
$0
### 5) How to check if previous command run successful ? ###
$?
### 6) How to get last line from a file ? ###
tail -1
### 7) How to get first line from a file ? ###
head -1
### 8) How to get 3rd element from each line from a file ? ###
awk '{print $3}'
### 9) How to get 2nd element from each line from a file, if first equal FIND ###
awk '{ if ($1 == "FIND") print $2}'
### 10) How to debug bash script ###
Add -xv to #!/bin/bash
Example
#!/bin/bash xv
### 11) Give an example how to write function ? ###
function example {
echo "Hello world!"
}
### 12) How to add string to string ? ###
V1="Hello"
V2="World"
V3=$V1+$V2
echo $V3
Output
Hello+World
### 13) How to add two integers ? ###
V1=1
V2=2
V3=$V1+$V2
echo $V3
Output
3
### 14) How to check if file exist on filesystem ? ###
if [ -f /var/log/messages ]
then
echo "File exists"
fi
### 15) Write down syntax for all loops in shell scripting ? ###
#### for loop : ####
for i in $( ls ); do
echo item: $i
done
#### while loop : ####
#!/bin/bash
COUNTER=0
while [ $COUNTER -lt 10 ]; do
echo The counter is $COUNTER
let COUNTER=COUNTER+1
done
until l#### ####oop :
#!/bin/bash
COUNTER=20
until [ $COUNTER -lt 10 ]; do
echo COUNTER $COUNTER
let COUNTER-=1
done
### 16) What it means by #!/bin/sh or #!/bin/bash at beginning of every script ? ###
That line tells which shell to use. #!/bin/bash script to execute using /bin/bash. In case of python script there there will be #!/usr/bin/python
### 17) How to get 10th line from the text file ? ###
head -10 file|tail -1
### 18) What is the first symbol in the bash script file ###
#
### 19) What would be the output of command: [ -z "" ] && echo 0 || echo 1 ###
0
### 20) What command "export" do ? ###
Makes variable public in subshells
### 21) How to run script in background ? ###
add "&" to the end of script
### 22) What "chmod 500 script" do ? ###
Makes script executable for script owner
### 23) What ">" do ? ###
Redirects output stream to file or another stream.
### 24) What difference between & and && ###
& - we using it when want to put script to background
&& - when we wand to execute command/script if first script was finished successfully
### 25) When we need "if" before [ condition ] ? ###
When we need to run several commands if condition meets.
### 26) What would be the output of the command: name=John && echo 'My name is $name' ###
My name is $name
### 27) Which is the symbol used for comments in bash shell scripting ? ###
#
### 28) What would be the output of command: echo ${new:-variable} ###
variable
### 29) What difference between ' and " quotes ? ###
' - we use it when do not want to evaluate variables to the values
" - all variables will be evaluated and its values will be assigned instead.
### 30) How to redirect stdout and stderr streams to log.txt file from script inside ? ###
Add "exec >log.txt 2>&1" as the first command in the script
### 31) How to get part of string variable with echo command only ? ###
echo ${variable:x:y}
x - start position
y - length
example:
variable="My name is Petras, and I am developer."
echo ${variable:11:6} # will display Petras
### 32) How to get home_dir with echo command only if string variable="User:123:321:/home/dir" is given ? ###
echo ${variable#*:*:*:}
or
echo ${variable##*:}
### 33) How to get “User” from the string above ? ###
echo ${variable%:*:*:*}
or
echo ${variable%%:*}
### 34) How to list users which UID less that 100 (awk) ? ###
awk -F: '$3<100' /etc/passwd
### 35) Write the program which counts unique primary groups for users and displays count and group name only ###
cat /etc/passwd|cut -d: -f4|sort|uniq -c|while read c g
do
{ echo $c; grep :$g: /etc/group|cut -d: -f1;}|xargs -n 2
done
### 36) How to change standard field separator to ":" in bash shell ? ###
IFS=":"
### 37) How to get variable length ? ###
${#variable}
### 38) How to print last 5 characters of variable ? ###
echo ${variable: -5}
### 39) What difference between ${variable:-10} and ${variable: -10} ? ###
${variable:-10} - gives 10 if variable was not assigned before
${variable: -10} - gives last 10 symbols of variable
### 40) How to substitute part of string with echo command only ? ###
echo ${variable//pattern/replacement}
### 41) Which command replaces string to uppercase ? ###
tr '[:lower:]' '[:upper:]'
### 42) How to count local accounts ? ###
wc -l /etc/passwd|cut -d" " -f1
or
cat /etc/passwd|wc -l
### 43) How to count words in a string without wc command ? ###
set ${string}
echo $#
### 44) Which one is correct "export $variable" or "export variable" ? ###
export variable
### 45) How to list files where second letter is a or b ? ###
ls -d ?[ab]*
### 46) How to add integers a to b and assign to c ? ###
c=$((a+b))
or
c=`expr $a + $b`
or
c=`echo "$a+$b"|bc`
### 47) How to remove all spaces from the string ? ###
echo $string|tr -d " "
### 48) Rewrite the command to print the sentence and converting variable to plural: item="car"; echo "I like $item" ? ###
item="car"; echo "I like ${item}s"
### 49) Write the command which will print numbers from 0 to 100 and display every third (0 3 6 9 …) ? ###
for i in {0..100..3}; do echo $i; done
or
for (( i=0; i<=100; i=i+3 )); do echo "Welcome $i times"; done
### 50) How to print all arguments provided to the script ? ###
echo $*
or
echo $@
### 51) What difference between [ $a == $b ] and [ $a -eq $b ] ###
[ $a == $b ] - should be used for string comparison
[ $a -eq $b ] - should be used for number tests
### 52) What difference between = and == ###
= - we using to assign value to variable
== - we using for string comparison
### 53) Write the command to test if $a greater than 12 ? ###
[ $a -gt 12 ]
### 54) Write the command to test if $b les or equal 12 ? ###
[ $b -le 12 ]
### 55) How to check if string begins with "abc" letters ? ###
[[ $string == abc* ]]
### 56) What difference between [[ $string == abc* ]] and [[ $string == "abc* ]] ###
[[ $string == abc* ]] - will check if string begins with abc letters
[[ $string == "abc*"" ]] - will check if string is equal exactly to abc*
### 57) How to list usernames which starts with ab or xy ? ###
egrep "^ab|^xy" /etc/passwd|cut -d: -f1
### 58) What $! means in bash ? ###
Most recent background command PID
### 59) What $? means ? ###
Most recent foreground exit status.
### 60) How to print PID of the current shell ? ###
echo $$
### 61) How to get number of passed arguments to the script ? ###
echo $#
### 62) What difference between $* and $@ ###
$* - gives all passed arguments to the script as a single string
$@ - gives all passed arguments to the script as delimited list. Delimiter $IFS
### 63) How to define array in bash ? ###
array=("Hi" "my" "name" "is")
### 64) How to print the first array element ? ###
echo ${array[0]}
### 65) How to print all array elements ? ###
echo ${array[@]}
### 66) How to print all array indexes ? ###
echo ${!array[@]}
### 67) How to remove array element with id 2 ? ###
unset array[2]
### 68) How to add new array element with id 333 ? ###
array[333]="New_element"
### 69) How shell script get input values ? ###
a) via parameters
./script param1 param2
b) via read command
read -p "Destination backup Server : " desthost
### 70) How can we use "expect" command in a script ? ###
/usr/bin/expect << EOD
spawn rsync -ar ${line} ${desthost}:${destpath}
expect "*?assword:*"
send "${password}\r"
expect eof
EOD
Good luck !! Please comment below if you have any new query or need answers for your questions. Let us know how well this helped for your interview :-)
--------------------------------------------------------------------------------
via: http://linoxide.com/linux-shell-script/shell-scripting-interview-questions-answers/
作者:[Petras Liumparas][a]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创翻译,[Linux中国](https://linux.cn/) 荣誉推出
[a]:http://linoxide.com/author/petrasl/