Monday, April 1, 2019

[Linux Tips] Screen, date

[Linux Tips] includes a series of very common tips for development in Linux environment. By default, I am using Ubuntu.

Screen.
This is used to create/maintain a session. This is very useful when you ssh to a remote machine and running some jobs in a interactive mode. Imagine if your network is disconnected, the thread to run your job will be killed. Screen can help you to create a session. You can attach (enter) or detach (quit) from the session.
1. To create a session
screen -S session_name
or simply,
screen

2. To list all sessions available.
screen -ls

3. Attach a session
screen -r session_name (a prefix is enough)

4. Detach a session
ctrl+a+d

5. Delete a session
screen -X -S session_name kill


Date
When you run some bash script. It's common that you want to name your output with current date/time.
In bash shell script you can do it as below.
dt_suffix=`date +'%d%m%H%M'`
Basically, it just assigns the date/time to a variable. And the string comes from date command. The +"%d%m%H%M" is the optional format parameter.


Bash Shell script, some common usages.
For-loop with an array.

declare -a your_array=(
foo
bar
baz
)
array_len=${#your_array[@]}
for ((i = 0; i< ${array_len}; i++));
do
echo "processing" ${your_array[${i}]}
# Do something here.
done

Check whether directory or file already exists.
file_path=PathToYourFile
dir_path=PathToYourDir
if [ ! -f ${file_path} ]; then
echo "File ${file_path} does not exist!"
else
echo "File ${file_path} already exists!"
fi

if [ ! -d ${dir_path} ]; then
echo "Directory ${dir_path} does not exist!"
else
echo "Directory ${dir_path} already exists!"
fi




No comments:

Post a Comment