The document discusses best practices for writing bash scripts. It covers topics like using shebangs, setting debug options, creating descriptive variables, command substitution, error handling, and profiling code. The document provides examples and tips for each topic. It emphasizes starting scripts with a header, using variables properly, checking for errors, and understanding the overall problem life cycle for writing better bash scripts.
The document discusses the Bash shell, which is the most popular shell in Linux. It is an sh-compatible shell that incorporates useful features from other shells like Korn and C shells. Bash can be used both interactively and for scripting purposes. The document provides examples of basic Bash scripts that use variables, command substitution, arithmetic evaluation, and conditional statements. It also discusses environmental variables and the read command.
This document provides an introduction and overview of shell scripting in Linux. It discusses what a shell script is, when they should and should not be used, examples of common shell scripts, and an introduction to programming features commonly used in shell scripts such as variables, conditionals, loops, command line arguments, and more. Key points covered include that shell scripts allow automating command execution, are useful for repetitive tasks, and come with programming features to customize behavior.
This document provides an introduction to shell scripting using the bash shell. It covers key concepts such as shell variables, command substitution, quoting, aliases, and initializing files. The shell acts as both a command-line interface and programming language. It executes commands, supports scripting through variables and control structures, and reads initialization files on startup to customize the environment. Well-formed shell scripts allow combining and sequencing commands to perform automated tasks.
This document provides an overview of shell scripting in Bash. It covers basic script syntax including the shebang line and running scripts. It discusses shell variables, control structures like for loops, and commands like echo, read, and printf for console I/O. The document also covers special variables, command line arguments, and provides exercises for students to practice shell scripting concepts.
A set of rules and best practices to write bash shell scripts. Following these rules, you will have less programming errors and spend less time debugging.
It also shows and explains a lot of features from bash you didn't event know existed :
Pattern removal: ${var##*/}
StrReplace: ${var//search/replace}
Options: set -o pipefail -o nounset -o noclobber
And many more...
The document discusses topics for an advanced Bash scripting class, including reviewing homework assignments, standard input/output/redirection, pipelines, functions, here documents, and arrays. Homework problems are presented on matching phone numbers in text and removing one-line comments from C/C++ files. Quiz problems cover writing to standard output and marking numeric constants in code files. Various Bash scripting concepts are reviewed like input/output redirection, case statements, loops, and functions.
This document provides an overview of Linux shell scripting (Bash) basics. It discusses writing scripts using editors like vi or vim, setting permissions using chmod, executing scripts, variables, arithmetic operations, file manipulation commands, pipes, reading from files, command substitution, background processes, arrays, output redirection, and input redirection. Examples are provided for many common scripting tasks and commands.
The document discusses the Bash shell, which is the most popular shell in Linux. It is an sh-compatible shell that incorporates useful features from other shells like Korn and C shells. Bash can be used both interactively and for scripting purposes. The document provides examples of basic Bash scripts that use variables, command substitution, arithmetic evaluation, and conditional statements. It also discusses environmental variables and the read command.
This document provides an introduction and overview of shell scripting in Linux. It discusses what a shell script is, when they should and should not be used, examples of common shell scripts, and an introduction to programming features commonly used in shell scripts such as variables, conditionals, loops, command line arguments, and more. Key points covered include that shell scripts allow automating command execution, are useful for repetitive tasks, and come with programming features to customize behavior.
This document provides an introduction to shell scripting using the bash shell. It covers key concepts such as shell variables, command substitution, quoting, aliases, and initializing files. The shell acts as both a command-line interface and programming language. It executes commands, supports scripting through variables and control structures, and reads initialization files on startup to customize the environment. Well-formed shell scripts allow combining and sequencing commands to perform automated tasks.
This document provides an overview of shell scripting in Bash. It covers basic script syntax including the shebang line and running scripts. It discusses shell variables, control structures like for loops, and commands like echo, read, and printf for console I/O. The document also covers special variables, command line arguments, and provides exercises for students to practice shell scripting concepts.
A set of rules and best practices to write bash shell scripts. Following these rules, you will have less programming errors and spend less time debugging.
It also shows and explains a lot of features from bash you didn't event know existed :
Pattern removal: ${var##*/}
StrReplace: ${var//search/replace}
Options: set -o pipefail -o nounset -o noclobber
And many more...
The document discusses topics for an advanced Bash scripting class, including reviewing homework assignments, standard input/output/redirection, pipelines, functions, here documents, and arrays. Homework problems are presented on matching phone numbers in text and removing one-line comments from C/C++ files. Quiz problems cover writing to standard output and marking numeric constants in code files. Various Bash scripting concepts are reviewed like input/output redirection, case statements, loops, and functions.
This document provides an overview of Linux shell scripting (Bash) basics. It discusses writing scripts using editors like vi or vim, setting permissions using chmod, executing scripts, variables, arithmetic operations, file manipulation commands, pipes, reading from files, command substitution, background processes, arrays, output redirection, and input redirection. Examples are provided for many common scripting tasks and commands.
This document provides an overview of Linux Bash shell scripting. It covers topics such as writing basic scripts, using variables and arithmetic, conditional statements, loops, reading/writing files, and more. Examples are given for many common scripting tasks like renaming files, checking disk space, searching files, generating random numbers, and calculating values. The document is intended to teach the basics of shell scripting through explanations and code samples.
Shell scripting involves writing scripts using bash commands. Key elements include:
1) Variables to store and manipulate data. Variables can hold strings or numbers.
2) Control structures like if/else, case, and loops (for, while, until) to make decisions and repeat tasks.
3) Functions to organize code into reusable blocks.
4) Reading/writing files for input/output.
5) Trapping signals like interrupts to handle errors gracefully.
The document discusses UNIX shell scripts, including what they are, their components, how to invoke them, examples of arguments, variables, command forms, and simple commands that can be used in shell scripts. It provides examples of shell scripts that perform tasks like iterating through a string and checking for available disk space.
The document provides information about shells in Linux operating systems. It defines what a kernel and shell are, explains why shells are used, describes different types of shells, and provides examples of shell scripting. The key points are:
- The kernel manages system resources and acts as an intermediary between hardware and software. A shell is a program that takes commands and runs them, providing an interface between the user and operating system.
- Shells are useful for automating tasks, combining commands to create new ones, and adding functionality to the operating system. Common shells include Bash, Bourne, C, Korn, and Tcsh.
- Shell scripts allow storing commands in files to automate tasks.
The document discusses shell scripting and provides examples of common shell scripting concepts and commands. It covers topics such as variables, conditionals, loops, functions, command execution, pipes, redirection, and here documents. Examples are provided to demonstrate how to write shell scripts using these different concepts and commands like echo, expr, case, if/else, for/while loops, functions, and more. The goal is to explain the basics of shell scripting through examples and outlines.
Unit 11 configuring the bash shell – shell scriptroot_fibo
The document discusses configuring the Bash shell in Linux. It covers using variables, aliases, startup files, and taking input. Key points include setting variables, common environment variables like PATH and PS1, creating aliases, how Bash parses commands, profile and bashrc startup files, and using positional parameters or read to take user input in scripts.
The document discusses shell scripts, including what they are, their components, how to invoke them, get help, and definitions of terms. It provides examples of shell scripting concepts like arguments, regular expressions, quoting, variables, command forms, and simple commands. It also includes examples of shell scripts and proposes homework assignments involving shell scripts.
Whether you call yourself a system administrator, developer, or DevOps sprint mediator, life is too short for sloppy shell scripts! In this talk, we look at how to improve them to stand the test of time. Michael will share how to create a good foundation for your scripts, so they run more reliable now and in the future. Your (future) colleagues might love you for it.
Focus areas of this presentation include error handling, security, style, and best practices. Also, it will cover (many) mistakes made by Michael over the last 20 years.
of 70UNIX Unbounded 5th EditionAmir Afzal .docxadkinspaige22
The document discusses the UNIX file system, including directories, file types, and important directories. It describes the hierarchical structure of directories with the root directory at the top, and subdirectories branching below. It defines regular files, directory files, and special files. It also outlines some important standard directories like /usr, /usr/docs, and users' home directories.
The document provides instructions for creating a PHP extension module that wraps the libares asynchronous DNS resolving library. It begins by explaining why such an extension is useful and covers generating an extension skeleton, configuring the build system to find libares, the key C API functions to expose, and the basic anatomy of a PHP extension.
The document provides instructions for creating a PHP extension module that wraps the libares asynchronous DNS resolving library. It begins by explaining why such an extension is useful and covers generating an extension skeleton, configuring the build system to find libares, the key C API functions to expose, and the basic anatomy of a PHP extension.
The document provides instructions for creating a PHP extension module that wraps the libares asynchronous DNS resolving library. It begins by explaining why such an extension is useful and covers generating an extension skeleton, configuring the build system to find libares, the key C API functions to expose, and the basic anatomy of a PHP extension.
The document provides instructions for creating a PHP extension module that wraps the libares asynchronous DNS resolving library. It begins by explaining why such an extension is useful and covers generating an extension skeleton, configuring the build system to find libares, the key C API functions to expose, and the basic anatomy of a PHP extension.
The document discusses extending the PHP programming language by creating a custom extension module that interfaces with the libares asynchronous DNS resolving library. It provides code snippets for the libares C API functions and proposed PHP wrapper functions. It also covers generating an extension skeleton, configuring the build system using config.m4 to locate the libares library, and the basic anatomy of a PHP extension, with the goal of creating a PHP extension that provides asynchronous DNS resolving.
The document provides instructions for creating a PHP extension module that wraps the libares asynchronous DNS resolving library. It begins by explaining why such an extension is useful and covers generating an extension skeleton, configuring the build system to find libares, the key C API functions to expose, and the basic anatomy of a PHP extension.
The document discusses shell scripts, including what a shell is, shell configuration, standard input/output/redirection, examples of shell scripts, and syntax for writing shell scripts such as for loops, if/else statements, and case statements. It also covers special parameters and gives an example homework assignment involving creating files for SPARCS 03 members and compressing them into a tarball.
Bash is a widely used command line shell for Linux and other Unix-like operating systems. The presentation discusses the history and evolution of Unix-based systems and introduces some of the key features of the Bash shell, including built-in commands, external commands, variables, expansion, loops, conditionals, I/O redirection, and user input handling. It highlights new features introduced in Bash version 4 such as associative arrays, expanded string manipulations, and coprocesses.
The Raspberry Pi is a series of credit card–sized single-board computers developed in the UK by the Raspberry Pi Foundation with the intention of promoting the teaching of basic computer science in schools.
The original Raspberry Pi and Raspberry Pi 2 are manufactured in several board configurations through licensed manufacturing agreements with Newark element14 (Premier Farnell), RS Components and Egoman. These companies sell the Raspberry Pi online. Egoman produces a version for distribution solely in China and Taiwan, which can be distinguished from other Pis by their red colouring and lack of FCC/CE marks. The hardware is the same across all manufacturers.
The original Raspberry Pi is based on the Broadcom BCM2835 system on a chip (SoC), which includes an ARM1176JZF-S 700 MHz processor, VideoCore IV GPU, and was originally shipped with 256 megabytes of RAM, later upgraded (models B and B+) to 512 MB. The system has Secure Digital (SD) (models A and B) or MicroSD (models A+ and B+) sockets for boot media and persistent storage.
Build applications with generative AI on Google CloudMárton Kodok
We will explore Vertex AI - Model Garden powered experiences, we are going to learn more about the integration of these generative AI APIs. We are going to see in action what the Gemini family of generative models are for developers to build and deploy AI-driven applications. Vertex AI includes a suite of foundation models, these are referred to as the PaLM and Gemini family of generative ai models, and they come in different versions. We are going to cover how to use via API to: - execute prompts in text and chat - cover multimodal use cases with image prompts. - finetune and distill to improve knowledge domains - run function calls with foundation models to optimize them for specific tasks. At the end of the session, developers will understand how to innovate with generative AI and develop apps using the generative ai industry trends.
This document provides an overview of Linux Bash shell scripting. It covers topics such as writing basic scripts, using variables and arithmetic, conditional statements, loops, reading/writing files, and more. Examples are given for many common scripting tasks like renaming files, checking disk space, searching files, generating random numbers, and calculating values. The document is intended to teach the basics of shell scripting through explanations and code samples.
Shell scripting involves writing scripts using bash commands. Key elements include:
1) Variables to store and manipulate data. Variables can hold strings or numbers.
2) Control structures like if/else, case, and loops (for, while, until) to make decisions and repeat tasks.
3) Functions to organize code into reusable blocks.
4) Reading/writing files for input/output.
5) Trapping signals like interrupts to handle errors gracefully.
The document discusses UNIX shell scripts, including what they are, their components, how to invoke them, examples of arguments, variables, command forms, and simple commands that can be used in shell scripts. It provides examples of shell scripts that perform tasks like iterating through a string and checking for available disk space.
The document provides information about shells in Linux operating systems. It defines what a kernel and shell are, explains why shells are used, describes different types of shells, and provides examples of shell scripting. The key points are:
- The kernel manages system resources and acts as an intermediary between hardware and software. A shell is a program that takes commands and runs them, providing an interface between the user and operating system.
- Shells are useful for automating tasks, combining commands to create new ones, and adding functionality to the operating system. Common shells include Bash, Bourne, C, Korn, and Tcsh.
- Shell scripts allow storing commands in files to automate tasks.
The document discusses shell scripting and provides examples of common shell scripting concepts and commands. It covers topics such as variables, conditionals, loops, functions, command execution, pipes, redirection, and here documents. Examples are provided to demonstrate how to write shell scripts using these different concepts and commands like echo, expr, case, if/else, for/while loops, functions, and more. The goal is to explain the basics of shell scripting through examples and outlines.
Unit 11 configuring the bash shell – shell scriptroot_fibo
The document discusses configuring the Bash shell in Linux. It covers using variables, aliases, startup files, and taking input. Key points include setting variables, common environment variables like PATH and PS1, creating aliases, how Bash parses commands, profile and bashrc startup files, and using positional parameters or read to take user input in scripts.
The document discusses shell scripts, including what they are, their components, how to invoke them, get help, and definitions of terms. It provides examples of shell scripting concepts like arguments, regular expressions, quoting, variables, command forms, and simple commands. It also includes examples of shell scripts and proposes homework assignments involving shell scripts.
Whether you call yourself a system administrator, developer, or DevOps sprint mediator, life is too short for sloppy shell scripts! In this talk, we look at how to improve them to stand the test of time. Michael will share how to create a good foundation for your scripts, so they run more reliable now and in the future. Your (future) colleagues might love you for it.
Focus areas of this presentation include error handling, security, style, and best practices. Also, it will cover (many) mistakes made by Michael over the last 20 years.
of 70UNIX Unbounded 5th EditionAmir Afzal .docxadkinspaige22
The document discusses the UNIX file system, including directories, file types, and important directories. It describes the hierarchical structure of directories with the root directory at the top, and subdirectories branching below. It defines regular files, directory files, and special files. It also outlines some important standard directories like /usr, /usr/docs, and users' home directories.
The document provides instructions for creating a PHP extension module that wraps the libares asynchronous DNS resolving library. It begins by explaining why such an extension is useful and covers generating an extension skeleton, configuring the build system to find libares, the key C API functions to expose, and the basic anatomy of a PHP extension.
The document provides instructions for creating a PHP extension module that wraps the libares asynchronous DNS resolving library. It begins by explaining why such an extension is useful and covers generating an extension skeleton, configuring the build system to find libares, the key C API functions to expose, and the basic anatomy of a PHP extension.
The document provides instructions for creating a PHP extension module that wraps the libares asynchronous DNS resolving library. It begins by explaining why such an extension is useful and covers generating an extension skeleton, configuring the build system to find libares, the key C API functions to expose, and the basic anatomy of a PHP extension.
The document provides instructions for creating a PHP extension module that wraps the libares asynchronous DNS resolving library. It begins by explaining why such an extension is useful and covers generating an extension skeleton, configuring the build system to find libares, the key C API functions to expose, and the basic anatomy of a PHP extension.
The document discusses extending the PHP programming language by creating a custom extension module that interfaces with the libares asynchronous DNS resolving library. It provides code snippets for the libares C API functions and proposed PHP wrapper functions. It also covers generating an extension skeleton, configuring the build system using config.m4 to locate the libares library, and the basic anatomy of a PHP extension, with the goal of creating a PHP extension that provides asynchronous DNS resolving.
The document provides instructions for creating a PHP extension module that wraps the libares asynchronous DNS resolving library. It begins by explaining why such an extension is useful and covers generating an extension skeleton, configuring the build system to find libares, the key C API functions to expose, and the basic anatomy of a PHP extension.
The document discusses shell scripts, including what a shell is, shell configuration, standard input/output/redirection, examples of shell scripts, and syntax for writing shell scripts such as for loops, if/else statements, and case statements. It also covers special parameters and gives an example homework assignment involving creating files for SPARCS 03 members and compressing them into a tarball.
Bash is a widely used command line shell for Linux and other Unix-like operating systems. The presentation discusses the history and evolution of Unix-based systems and introduces some of the key features of the Bash shell, including built-in commands, external commands, variables, expansion, loops, conditionals, I/O redirection, and user input handling. It highlights new features introduced in Bash version 4 such as associative arrays, expanded string manipulations, and coprocesses.
The Raspberry Pi is a series of credit card–sized single-board computers developed in the UK by the Raspberry Pi Foundation with the intention of promoting the teaching of basic computer science in schools.
The original Raspberry Pi and Raspberry Pi 2 are manufactured in several board configurations through licensed manufacturing agreements with Newark element14 (Premier Farnell), RS Components and Egoman. These companies sell the Raspberry Pi online. Egoman produces a version for distribution solely in China and Taiwan, which can be distinguished from other Pis by their red colouring and lack of FCC/CE marks. The hardware is the same across all manufacturers.
The original Raspberry Pi is based on the Broadcom BCM2835 system on a chip (SoC), which includes an ARM1176JZF-S 700 MHz processor, VideoCore IV GPU, and was originally shipped with 256 megabytes of RAM, later upgraded (models B and B+) to 512 MB. The system has Secure Digital (SD) (models A and B) or MicroSD (models A+ and B+) sockets for boot media and persistent storage.
Build applications with generative AI on Google CloudMárton Kodok
We will explore Vertex AI - Model Garden powered experiences, we are going to learn more about the integration of these generative AI APIs. We are going to see in action what the Gemini family of generative models are for developers to build and deploy AI-driven applications. Vertex AI includes a suite of foundation models, these are referred to as the PaLM and Gemini family of generative ai models, and they come in different versions. We are going to cover how to use via API to: - execute prompts in text and chat - cover multimodal use cases with image prompts. - finetune and distill to improve knowledge domains - run function calls with foundation models to optimize them for specific tasks. At the end of the session, developers will understand how to innovate with generative AI and develop apps using the generative ai industry trends.
End-to-end pipeline agility - Berlin Buzzwords 2024Lars Albertsson
We describe how we achieve high change agility in data engineering by eliminating the fear of breaking downstream data pipelines through end-to-end pipeline testing, and by using schema metaprogramming to safely eliminate boilerplate involved in changes that affect whole pipelines.
A quick poll on agility in changing pipelines from end to end indicated a huge span in capabilities. For the question "How long time does it take for all downstream pipelines to be adapted to an upstream change," the median response was 6 months, but some respondents could do it in less than a day. When quantitative data engineering differences between the best and worst are measured, the span is often 100x-1000x, sometimes even more.
A long time ago, we suffered at Spotify from fear of changing pipelines due to not knowing what the impact might be downstream. We made plans for a technical solution to test pipelines end-to-end to mitigate that fear, but the effort failed for cultural reasons. We eventually solved this challenge, but in a different context. In this presentation we will describe how we test full pipelines effectively by manipulating workflow orchestration, which enables us to make changes in pipelines without fear of breaking downstream.
Making schema changes that affect many jobs also involves a lot of toil and boilerplate. Using schema-on-read mitigates some of it, but has drawbacks since it makes it more difficult to detect errors early. We will describe how we have rejected this tradeoff by applying schema metaprogramming, eliminating boilerplate but keeping the protection of static typing, thereby further improving agility to quickly modify data pipelines without fear.
"Financial Odyssey: Navigating Past Performance Through Diverse Analytical Lens"sameer shah
Embark on a captivating financial journey with 'Financial Odyssey,' our hackathon project. Delve deep into the past performance of two companies as we employ an array of financial statement analysis techniques. From ratio analysis to trend analysis, uncover insights crucial for informed decision-making in the dynamic world of finance."
Open Source Contributions to Postgres: The Basics POSETTE 2024ElizabethGarrettChri
Postgres is the most advanced open-source database in the world and it's supported by a community, not a single company. So how does this work? How does code actually get into Postgres? I recently had a patch submitted and committed and I want to share what I learned in that process. I’ll give you an overview of Postgres versions and how the underlying project codebase functions. I’ll also show you the process for submitting a patch and getting that tested and committed.
4th Modern Marketing Reckoner by MMA Global India & Group M: 60+ experts on W...Social Samosa
The Modern Marketing Reckoner (MMR) is a comprehensive resource packed with POVs from 60+ industry leaders on how AI is transforming the 4 key pillars of marketing – product, place, price and promotions.
2. sh is a specification, bash is the implementation.
(1) sh
Strictly speaking, sh (or the Shell Command Language) is a programming language described by
the POSIX standard. The key here is that sh isn’t really a programming language in itself. It is just a
specification. Specification is a detailed description of the syntax and semantics of that language.
Specification doesn’t include an implementation.
(2) bash
There are different operating systems with their own shells and kernel. Bash is the shell for the GNU
operating system. But we can also say that bash is a programming language.
sh vs bash
3. (1) Variables
(2) Conditionals
(3) Loops
(4) Regex
(5) Mathematical Skill
(6) Debugging Skill
(7) Understand Problem life cycle
Basics for better bash scripts
4. (1) Variables
#!/usr/bin/env bash
LINK_OR_DIR="/tmp/coordinator"
if [ -d "$LINK_OR_DIR" ]; then
# If Condition is satisfied
else:
# If Condition is not satisfies
fi
(2) Conditionals
(3) Loops
(4) Regex
(5) Mathematical Skill
(6) Debugging Skill
(7) Understand Problem life cycle
Basics for better bash scripts
5. (1) Variables
(2) Conditionals
#!/usr/bin/env bash
if [ -d "$LINK_OR_DIR" ]; then
# If Condition is satisfied
else:
# If Condition is not satisfies
fi
## With the same syntax you can use:
## -e: any kind of archive
## -f: file
## -h: symbolic link
## -r: readable file
## -w: writable file
## -x: executable file
## -s: file size greater than zero
## -d: check if it's a directory
## -L: check if it's a symbolic link
## -z: if the length of string is zero
## -n: length of string is non-zero
(3) Loops
(4) Regex
(5) Mathematical Skill
(6) Debugging Skill
(7) Problem life cycle
Basics for better bash scripts
6. (1) Variables
(2) Conditionals
(3) Loops
#!/usr/bin/env bash
## While loop
while [ <some test> ]
do
<commands>
done
## Until loop
until [ <some test> ]
do
<commands>
done
## For loop
for var in <list>
do
<commands>
done
(1) Regex
(2) Mathematical Skill
(3) Debugging Skill
(4) Understand Problem life cycle
Basics for better bash scripts
7. (1) Variables
(2) Conditionals
(3) Loops
(4) Regex
#!/usr/bin/env bash
t="abc123"
[[ "$t" == abc* ]] # true (globbing)
[[ "$t" == "abc*" ]] # false (literal matching)
[[ "$t" =~ [abc]+[123]+ ]] # true (regular expression)
[[ "$t" =~ "abc*" ]] # false (literal matching)
Note, that starting with bash version 3.2 the regular or globbing expression
must not be quoted. If your expression contains whitespace you can store it in a variable:
r="a b+"
[[ "a bbb" =~ $r ]] # true
(5) Mathematical Skill
(6) Debugging Skill
(7) Understand Problem life cycle
Basics for better bash scripts
8. (1) Variables
(2) Conditionals
(3) Loops
(4) Regex
(5) Mathematical Skill
Matrix algebra
Logical gates
(6) Debugging Skill
(7) Understand Problem life cycle
Basics for better bash scripts
9. (1) Variables
(2) Conditionals
(3) Loops
(4) Regex
(5) Mathematical Skill
(6) Debugging Skill
1. Reproduce
Before you scramble and try to fix the bug as soon as possible, make sure you can actually reproduce it first.
2. Investigate
Find the bug in the code and the cause!
3. Know Your Error Codes
This is a bit of strange one to hear, but given how fundamental are worth here.
4. Fix & Verify
Now verify that it is actually fixed and, more importantly, that your fix didn't break anything else.
(7) Understand Problem life cycle
Basics for better bash scripts
10. (1) Variables
(2) Conditionals
(3) Loops
(4) Regex
(5) Mathematical Skill
(6) Debugging Skill
(7) Understand Problem life cycle
Basics for better bash scripts
11. #!/usr/bin/env bash
##
## HEADER
# Include other bash file
source helper.sh
# Read a file and execute line by line
for server in $(cat servers.txt); do
echo "Server Info: ${server} n"
done
# Ask for confirmation
read -p "You need choice?" yn
case $yn in
[yY] | [yY][Ee][Ss] )
# YOUR YES CODE HERE
;;
[nN] | [nN][Oo] )
# YOUR NO CODE HERE
;;
* ) echo "Please answer yes or no.";;
Esac
# Create File/Directory if not Exists
[ ! -f /tmp/testfile.log ] && touch /tmp/testfile.log
[ ! -d /tmp/mydir ] && mkdir -p /tmp/mydir
# If not active node version 8 then activate using nvm
NVM=https://raw.githubusercontent.com/nvm-
sh/nvm/v0.38.0/install.sh
if [ -x "$(command -v nvm)" ]; then
sh -c "$(curl -fsSL $NVM)"
source ~/.profile
fi
# finds out where bash is on your system
Whereisbash=$(whereis bash)
# Check command executed or not
<command-here>
if [ $? -eq 0 ]; then
echo OK
else
echo FAIL
Fi
# Check profile data on execution time
start=$(date +%s)
# YOUR NO CODE HERE
end=$(date +%s)
echo "Elapsed Time: $(($end-$start)) seconds"
Example:
13. (1) Always start with a shebang with header description
(2) Start debug options when developing
(3) Create descriptive variable names
(4) Use $(command) for command substitution
(5) Before you exit on error describe the problem
5 Tips for better bash scripts
14. (1) Always start with a shebang with header description
#!/usr/bin/env bash
##
## DESCRIPTION: [Description]
## AUTHOR: [Author]
## DATE: [XX_XX_XXXX.XX_XX_XX]
## VERSION: [Version]
## USAGE: [Usage]
##
NOTE:
# How To Start A shebang
#!/bin/sh [For sh scripting]
#!/bin/bash [For bash scripting]
#!/usr/bin/perl [For perl programming]
#!/bin/awk -f [For awk scripting]
#!/usr/bin/env bash [For more portable than #!/bin/bash]
(2) Start debug options when developing
(3) Create descriptive variable names
(4) Use $(command) for command substitution
(5) Before you exit on error describe the problem
5 Tips for better bash scripts
15. (1) Always start with a shebang with header description
(2) Start debug options when developing
SHORTFORM FULLFORM DESCRIPTION
set -f set -o noglob Disable file name generation using metacharacters (globbing).
set –v set -o verbose Prints shell input lines as they are read.
set –x set -o xtrace Print command traces before executing command.
set -o pipefail Return the exit status of the last command piped command
set -u set -o nounset Exit if an unsed variable is used
set –e set -o errexit let script exit if a command fails
set -n dry run shell script commands
Usage:
#!/usr/bin/env bash
set -o errexit
set -o nounset
set -o pipefail
OR
#!/usr/bin/env bash
set -xv # this line will enable debug
# --- YOUR CODE HERE --- #
set +xv # this line will disable debug
(3) Create descriptive variable names
(4) Use $(command) for command substitution
(5) Before you exit on error describe the problem
5 Tips for better bash scripts
16. (1) Always start with a shebang with header description
(2) Start debug options when developing
(3) Create descriptive variable names
## Strings should have the form name=value.
## Ideally variable names should only consist uppercase letters, digits, and the ‘_’ (underscore).
## Variable Names shall not contain the character ‘=’ or ‘-‘
## No spaces before or after that equal sign
## Double quotes around every parameter expansion
## Don’t start Variable Name with special characters or Numbers
Example: song="My song.mp3"
(4) Use $(command) for command substitution
(5) Before you exit on error describe the problem
5 Tips for better bash scripts
17. (1) Always start with a shebang with header description
(2) Start debug options when developing
(3) Create descriptive variable names
(4) Use $(command) for command substitution
#!/usr/bin/env bash
##
## DESCRIPTION: [Description]
## AUTHOR: [Author]
## DATE: [XX_XX_XXXX.XX_XX_XX]
## VERSION: [Version]
## USAGE: [Usage]
##
users=$(cat users.txt)
(5) Before you exit on error describe the problem
5 Tips for better bash scripts
18. (1) Always start with a shebang with header description
(2) Start debug options when developing
(3) Create descriptive variable names
(4) Use $(command) for command substitution
(5) Before you exit on error describe the problem
Bash Exit Codes
The exit code is a number between 0 and 255
• Success – A zero (0) value represents success.
• failure – A non-zero exit-code represents failure.
#!/usr/bin/env bash
listall=$(ls –la)
if [ $? -eq 0 ]; then
echo OK
else
echo FAIL
fi
NOTE: $?-- Holds the status of the last pipe close, back-quote string, or system() function.
5 Tips for better bash scripts
20. (1) Prerequisites
(2) Program Logic
(3) Create and Moving files/directories
(4) Change Owner access
(5) Create Soft/Hard links
(6) Check installation
High level view for better bash scripts
21. #!/usr/bin/env bash
##
## HEADER
# PREREQUISITES
# Include other bash file
source helper.sh
# PROGRAM LOGIC
# Read a file and execute line by line
for server in $(cat servers.txt); do
echo "Server Info: ${server} n"
done
# Ask for confirmation
read -p "You need choice?" yn
case $yn in
[yY] | [yY][Ee][Ss] )
# YOUR YES CODE HERE
;;
[nN] | [nN][Oo] )
# YOUR NO CODE HERE
;;
* ) echo "Please answer yes or no.";;
esac
# CREATE FILES, DIRECTORIES
# Create File/Directory if not Exists
[ ! -f /tmp/testfile.log ] && touch /tmp/testfile.log
[ ! -d /tmp/mydir ] && mkdir -p /tmp/mydir
# If not active node version 8 then activate using nvm
NVM=https://raw.githubusercontent.com/nvm-
sh/nvm/v0.38.0/install.sh
if [ -x "$(command -v nvm)" ]; then
sh -c "$(curl -fsSL $NVM)"
source ~/.profile
fi
# finds out where bash is on your system
Whereisbash=$(whereis bash)
# CHECK INSTALLATION
# Check command executed or not
<command-here>
if [ $? -eq 0 ]; then
echo OK
else
echo FAIL
Fi
# PROFILE YOUR CODE
# Check profile data on execution time
start=$(date +%s)
# YOUR NO CODE HERE
end=$(date +%s)
echo "Elapsed Time: $(($end-$start)) seconds"
Example: