≡ Menu

tmp

The source command read and execute commands from a file. My parent.sh script source a script called child.sh. But, child.sh script can not determine it's own location using $0. By default, $0 gives parent script location. How do I find out a script that is sourced at the command line can determine it's own location? My sample script:

#!/bin/bash
# /var/www/html/java/tasks/child.sh 
_me="$0"
 
 
# I want /var/www/html/java/tasks in _currentdir 
_currentdir="${_me%/*}"
echo "${_currentdir}"
 

When I run from parent.sh:

source child.sh

OR

source /var/www/html/java/tasks/child.sh

The $_currentdir is set to be the directory where parent.sh lives which is in /root/scripts/java/helper or . (current) directory. How do I fix this problem?
[click to continue…]

UNIX / Linux: awk Add Two Numbers

How do I add two numbers using awk? How do I calculate all incoming number stream on fly and display the total using awk?
[click to continue…]

I need to get a list of sizes in human readable du output format. How do I get the output for du command in GB under Linux or UNIX operating systems?
[click to continue…]

How to: create a temporary file securely

Q. How do I create a temporary file securely under UNIX Bash shell?

A. There are many ways:
[a] mktemp command - make temporary unique filename

[b] $RANDOM - Use $RANDOM variable

mktemp command

From the man page:

The mktemp utility takes the given filename template and overwrites a portion of it to create a unique filename. The template may be any filename with some number of ‘Xs’ appended to it, for example /tmp/tfile.XXXXXXXXXX.

For example, create a temporary file:
$ mktemp /tmp/output.XXXXXXXXXX
Output:

/tmp/output.qBYDtF7199

Send ls command output to /tmp/output.qBYDtF7199:
$ ls > /tmp/output.qBYDtF7199
However, you may need to store temporary file name /tmp/output.qBYDtF7199 to a shell variable:
TMPFILE=$(mktemp /tmp/output.XXXXXXXXXX)
ls > $TMPFILE

Create a temporary directory

The -d option makes a directory instead of a file.
TMPDIR=$(mktemp -d /tmp/output.XXXXXXXXXX)
cd $TMPDIR
# do something

Another example:

TMPFILE=‘mktemp -t /tmp/out.myapp.XXXXXXXXXX‘ && {
    # Safe to use $TMPFILE in this block
    echo data > $TMPFILE
    ...
   # do something
   # clean up
    rm -f $TMPFILE
}

Using $RANDOM variable

Bash also provide $RANDOM variable with random value, you can use the same to create a file or directory:

TEMFILE=/tmp/$RANDOM
> $TEMFILE
# create directory
TEMDIR=/tmp/$RANDOM.$RANDOM
mkdir $TEMDIR
# do something...

How do I replace a string with another string in all files? For example, ~/foo directory has 100s of text file and I'd like to find out xyz string and replace with abc. I'd like to use sed or any other tool to replace all occurrence of the word.
[click to continue…]