Bash – Get Current Directory or Folder Name (Without Full Path) In Bash Script

No need for basename, and especially no need for a subshell running pwd (which adds an extra, and expensive, fork operation); the shell can do this internally using parameter expansion: result=${PWD##*/} # to assign to a variable result=${result:-/} # to correct for the case where PWD=/ printf ‘%s\n’ “${PWD##*/}” # to print to stdout # … Read more

Should I put #! (shebang) in Python scripts, and what form should it take?

The shebang line in any script determines the script’s ability to be executed like a standalone executable without typing python beforehand in the terminal or when double clicking it in a file manager (when configured properly). It isn’t necessary but generally put there so when someone sees the file opened in an editor, they immediately … Read more

Defining a variable with or without export

export makes the variable available to sub-processes. That is, export name=value means that the variable name is available to any process you run from that shell process. If you want a process to make use of this variable, use export, and run the process from that shell. name=value means the variable scope is restricted to … Read more

Replace one substring for another string in shell script

To replace the first occurrence of a pattern with a given string, use ${parameter/pattern/string}: #!/bin/bash firstString=”I love Suzi and Marry” secondString=”Sara” echo “${firstString/Suzi/”$secondString”}” # prints ‘I love Sara and Marry’ To replace all occurrences, use ${parameter//pattern/string}: message=”The secret code is 12345″ echo “${message//[0-9]/X}” # prints ‘The secret code is XXXXX’ (This is documented in the … Read more

Why do people write #!/usr/bin/env python on the first line of a Python script?

If you have several versions of Python installed, /usr/bin/env will ensure the interpreter used is the first one on your environment’s $PATH. The alternative would be to hardcode something like #!/usr/bin/python; that’s ok, but less flexible. In Unix, an executable file that’s meant to be interpreted can indicate what interpreter to use by having a … Read more

Running shell command and capturing the output

In all officially maintained versions of Python, the simplest approach is to use the subprocess.check_output function: >>> subprocess.check_output([‘ls’, ‘-l’]) b’total 0\n-rw-r–r– 1 memyself staff 0 Mar 14 11:04 files\n’ check_output runs a single program that takes only arguments as input.1 It returns the result exactly as printed to stdout. If you need to write input … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)