fbpx source Command in Linux: Load Scripts and Variables | Certificação Linux

Linux source Command: Load Functions and Variables from Shell Files

📅 01/01/2019 ⏱ 2 min ✍️ Uira Ribeiro
Linuxcommands
Linux source Command: Load Functions and Variables from Shell Files
Exam Pass App — mais de 7.000 questões LPI, offline, em 5 idiomas, disponível no Android e na App Store
Available on
Google Play
Available on
App Store

The source command is used to read a library file with several functions for the shell in a script file or the command prompt. It searches for library files located in the directories of the PATH variable or from a specific file.

Examples:

$ source funcoes.sh$ source /caminho/ate/diretório/funcoes.sh arg1 arg2

In the example below, we will create a file called minhabiblioteca.sh with the following content:

#!/bin/basheh_o_root(){   [ $(id -u) -eq 0 ] && return $TRUE || return $FALSE}

This file contains a function called "eh_o_root" that returns true if the uid of the logged in user equals zero (root) or false when it returns another value.

Now let's create a script called meuscript.sh that will use minhabiblioteca.sh as a source of functions:

#!/bin/bash# Vamos ler o minhabiblioteca.sh com o comando sourcesource minhabiblioteca.sheh_o_root && echo “Você é o Root.” || echo “Você é um usuário comum.”

Now let's change the permission of meuscript.sh to executable:

$ chmod +x meuscript.sh

When executing meuscript.sh:

$ ./meuscript.shVocê é um usuário comum.

The source command is very useful for reading a library of functions or variables that can be used by several shell scripts.

Learn much more about Linux in our online course. You can enroll here. If you already have an account, or want to create one, just log in or create your user here.

Did you like it? Share

Uira Ribeiro

Prof. Uirá Ribeiro

Chair do Board do Linux Professional Institute

After years of watching professionals waste hours on simple tasks because they didn't know the right Linux tools, I decided to teach.
Today I'm the author of most of LPI's official Learning Materials and mentor to over 14,000 certified students.

See my full story →

That was just one piece. The course teaches the whole path — from your first command to exam day.

Certificação Linux — a plataforma líder em certificações Linux no Brasil
WhatsApp