Wednesday, April 10, 2019

[Linux Tips] Bash Shell (I)

1.to declare a new variable:
variable_name=initial_value;
2. in linux, before you run you shell-script, you need to change the mod of script file.
chmod 755 script_name
(This will change the mode of file to owner: rwx, group and others: r-x)
maybe ./script_name is more precisely. This command will add the permission of execution to this script file.
3. use a variable:
$variable_name
4. to do something on all certain files under current directory:
for file in ` ls *[^smp].byu `
do
# do something on every file $file
echo $file
done

if ...
do
else
fi # end of if :)

5. substring:
To take part of a string:
string="test"
substring=${string:1:2}
echo subtring
result: es
note:
substring=${string_variable_name:starting_position:length}
The string starting position is zero-based.

6. Searching and Replacing Substrings within Strings:
In this method you can replace one or more instances of a string with another string. Here is the basic syntax:
alpha="This is a test string in which the word \"test\" is replaced."
beta="${alpha/test/replace}"
The string "beta" now contains an edited version of the original string in which the first case of the word "test" has been replaced by "replace". To replace all cases, not just the first, use this syntax:
beta="${alpha//test/replace}"

Note the double "//" symbol.

Here is an example in which we replace one string with another in a multi-line block of text:

list="cricket frog cat dog"
poem="I wanna be a x\n\
A x is what I'd love to be\n\
If I became a x\n\
How happy I would be.\n"
for critter in $list; do
echo -e ${poem//x/$critter}
done
Run this example:
$ ./myscript.sh
result:
I wanna be a cricket
A cricket is what I'd love to be
If I became a cricket
How happy I would be.
I wanna be a frog
A frog is what I'd love to be
If I became a frog
How happy I would be.
I wanna be a cat
A cat is what I'd love to be
If I became a cat
How happy I would be.
I wanna be a dog
A dog is what I'd love to be
If I became a dog
How happy I would be.
Silly example, huh? It should be obvious that this search & replace capability could have many more useful purposes.

7. to run matlab (e.g plot some graph) without start matlab window
matlab -nodesktop -nosplash -r "plot_data;quit;"
#here we have a .m file named "plot_data.m" under current dir

No comments:

Post a Comment