Category: Linux

You got to love Linux. Not only that it is free, but it is also very strong, stable, and widely used.

  • Allowing a linux/unix user all sudo access without password

    /etc/sudoers

    yourusername ALL=(ALL) NOPASSWD:ALL

  • Find with xargs

    Search all files under current directory, look for xml node ‘‘, copy and print that node. Send the output to a file.

    find . |xargs -n1 xmlstarlet sel -t -c “//processorInfo[@ruleType=’store’]” 2>/dev/null > /cygdrive/b/allstore.txt

  • XMLStartlet – Command line xml queries

    xmlstarlet sel -t -c “//YOUR_NODE_ELEMENT_TAG_NAME[@ATTRIBUTE_NAME=’ATTRIBUTE_VALUE’]” YOUR_XML_FILE.xml

  • Bash Scripting templates


    # ==========================
    # Bash tips
    # ==========================

    # Run bash by
    $ /bin/bash scriptname.sh
    $ /bin/bash scriptname.sh +x # debug mode

    # Or put the next line on the 1st line of your file.
    #!/bin/bash -x

    ## Double round braket for integer
    if (( $MYINT < 10 ]] #or: = ## Double square braket for string if [[ $USER = "ron" ]] #or: != then echo "Hello ron" else echo "Hello Stranger" fi $ date +%x # shows only the date 07/02/13 depending on locale, currently en_CA $ LANG=en_US $ date +%x # shows only the date 02/07/13 # ========================== # vi tips # ========================== # Using normal mode # Delete line at the cursor # type dd # Insert at cursor # type i # Insert after the cursor (append) # type a k J o # To bring in (read in) the content of an extrnal file into your current file :r ~/snippets/if # To read in a result of an executable, such as date use the :r! :r!date :r!date "+\%x" # Macro normal mode :map # Macro insert mode :map! # Macro F2 to insert text: "#This file was created on 2014-05-03" :map i#This file was created on :r!date "+\%x" kJ

    put the line above to .vimrc
    map i#!/bin/bash
    map o#This file was created on :r!date "+\%x" kJ

  • Enabling SSH (https) for Apache 2 in Ubuntu/Mint/Possibly other Debian distro


    # Intall apache
    $ sudo apt-get install apache2

    # Enable SSL module
    $ sudo a2enmod ssl

    # Restart Apache
    $ sudo service apache2 restart

    # Create a directory to store the SSLCertificateFile and SSLCertificateKeyFile
    $ mkdir /etc/apache2/ssl

    # Generate the keys
    $ sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/apache2/ssl/apache.key -out /etc/apache2/ssl/apache.crt
    Generating a 2048 bit RSA private key
    ...................................+++
    ................................+++
    writing new private key to '/etc/apache2/ssl/apache.key'
    -----
    You are about to be asked to enter information that will be incorporated
    into your certificate request.
    What you are about to enter is what is called a Distinguished Name or a DN.
    There are quite a few fields but you can leave some blank
    For some fields there will be a default value,
    If you enter '.', the field will be left blank.
    -----
    Country Name (2 letter code) [AU]:CA
    State or Province Name (full name) [Some-State]:Ontario
    Locality Name (eg, city) []:Ottawa
    Organization Name (eg, company) [Internet Widgits Pty Ltd]:Ronald Pringadi
    Organizational Unit Name (eg, section) []:Engineering
    Common Name (e.g. server FQDN or YOUR name) []:ronald-mint.com
    Email Address []:webmaster@some-cool-website.com

    # Edit your hosts file and add "127.0.0.1 some-cool-website.com"
    $ gedit /etc/hosts

    # Edit your sites-available ssl config
    $ gedit /etc/apache2/sites-available/default-ssl.conf
    # Make sure you add the following line under the email
    ServerName some-cool-website:443
    # Also replace
    SSLCertificateFile /etc/apache2/ssl/apache.crt
    SSLCertificateKeyFile /etc/apache2/ssl/apache.key

    # Activte site
    $ sudo a2ensite default-ssl

    # Reload Apache
    $ sudo service apache2 reload

    Open your browser and point it to https://some-cool-website.com. The browser will prompt you that the website is using a self-sign certificate, and do you want to continue and accept that certificate. Answer yes and that’s all to it

  • Directory sharing between Linux and Windows

    1. Sharing/serving a Linux directory to Windows
    $ sudo apt-get install samba
    $ sudo smbpasswd -a USERNAME
    $ mkdir /home/USERNAME/sharedfolder
    $ sudo vi /etc/samba/smb.conf

    [sharedfolder]
    path = /home/USERNAME/sharedfolder
    available = yes
    valid users = USERNAME
    read only = no
    browsable = yes
    public = yes
    writable = yes

    $ sudo restart smbd
    Soruce: http://askubuntu.com/questions/19361/cant-access-ubuntus-shared-folders-from-windows-7

    2. Linux Accessing Windows Shared Directory
    sudo mount -t cifs //192.168.1.101/sharedirectoryabc -o username=YOURUSERNAME,password=YOURPASSWORD /home/userabc/sharedirectoryabc

  • Getting the current filename using bash


    $ cat ./testfilename.sh
    #!/bin/bash
    fullfile=`basename $0`
    filename=$(basename "$fullfile")
    echo "filename:"$filename
    extension="${filename##*.}"
    echo "extension:"$extension
    justfilename="${filename%.*}"
    echo "justfilename:"$justfilename

    $ ./testfilename.sh
    filename:testfilename.sh
    extension:sh
    justfilename:testfilename

  • Customize your Vim editor using .vimrc

    Quick notes:
    – imap is for when you are in insert mode
    – map is when your are in command mode

    Thus when you are in the insert mode, sometime you need to exit to the command mode first using the esc key.
    The i is for going back to the inser mode. The cr key is the Enter key.

    The script below will make vim to:
    – Find and Replace when I hit F3
    – Undo when I hit F9
    – Saves when I hit F10
    – Quit when I hit F12
    – Prints a debugging statement for PHP when I press F8
    – Also disables the REPLACE mode


    """"""""""""""""""""""""""""""""""""""
    " Quick commands using F keys
    """""""""""""""""""""""""""""""""""""""
    :imap :%s/search/replace/gc
    :map :%s/search/replace/gc

    :imap :ui
    :map :ui

    :imap :w!i
    :map :w!i

    :imap :q!
    :map :q!

    :imap error_log("\n".__FILE__ . ' ['. __LINE__. '] ' . __CLASS__.'::'.__FUNCTION__.'() D>'. print_r(, true));
    :map ierror_log("\n".__FILE__ . ' ['. __LINE__. '] ' . __CLASS__.'::'.__FUNCTION__.'() D>'. print_r(, true));

    """""""""""""""""""""""""""""""""""""""
    " Disable REPLACE mode
    """""""""""""""""""""""""""""""""""""""
    function s:ForbidReplace()
    if v:insertmode isnot# 'i'
    call feedkeys("\", "n")
    endif
    endfunction
    augroup ForbidReplaceMode
    autocmd!
    autocmd InsertEnter * call s:ForbidReplace()
    autocmd InsertChange * call s:ForbidReplace()
    augroup END

  • Search and replace withing a file


    sed -i -e"s/SEARCH_TEXT/REPPLACE_TEXT/g" FILENAME.txt

    # another example using bakup
    sed -i.bak -e"s/SEARCH_TEXT/REPPLACE_TEXT/g" FILENAME.txt

    # another example using variable
    sed -i -e"s/\/pathname/\/pathname-$date/g" "filename-"$date".xml"

  • Bash Scripting Basics (Variable Assignment, If, Loop)


    #!/bin/bash
    ##################################################
    # Benchmark the processing time when wkhtmltopdf
    # converts an html file to a pdf file
    ##################################################

    if [[ $1 = "" || $2 = "" || $3 = "" ]]; then
    echo "Usage: `basename $0` sourceFile.html destinationFile.pdf iteartionRunTime"
    else
    _min=9999
    _max=0
    _total=0
    _iteration=$3
    for (( _i=1; _i<=$_iteration; _i++ )) do _start_time=`date +%s` echo "running $_i" ~MYUSER/bin/benchmarkWkhtmltopdf.sh $1 $2 > /dev/null 2>&1
    _end_time=`date +%s`
    _processing_time=$((_end_time-_start_time))
    if [ "$_processing_time" -lt "$_min" ]; then
    _min=$_processing_time
    fi
    if [ "$_processing_time" -gt "$_max" ]; then
    _max=$_processing_time
    fi
    _total=$(($_total+$_processing_time))
    done
    _processing_time_average=$(echo - | awk "{print $_total/$_iteration}")
    echo "Processing time avg: $_processing_time_average min:$_min max:$_max total:$_total"
    fi