i have a main bash script in an ubuntu server. i want to store my always used codes on another file or script. then i want to access these code blocks from my main scripts what should i do
Assistant
To modularize your Bash scripts on your Ubuntu server and store commonly used code blocks in separate files, you can define functions in those files and then source them into your main script. Here’s how you can do it:
Step 1: Create a Separate File for Your Reusable Code
Create a new file to store your reusable functions. You can name it something like common_functions.sh.
bash
nano ~/common_functions.sh
In common_functions.sh, define your functions. For example:
bash
#!/bin/bash
function greet {
echo "Hello, $1!"
}
function add {
echo "$(($1 + $2))"
}
Save and close the file.
Step 2: Make Your Function File Executable (Optional)
Though it's not strictly necessary to make it executable for sourcing, it can be a good practice.
bash
chmod +x ~/common_functions.sh
Step 3: Source the Functions in Your Main Script
Open your main script (let's call it main_script.sh):
bash
nano ~/main_script.sh
At the top of main_script.sh, source common_functions.sh:
bash
#!/bin/bash
# Source the common functions
source ~/common_functions.sh
# Now you can use the functions defined in common_functions.sh
greet "Alice"
result=$(add 5 10)
echo "The sum is: $result"
Save and close the file.
Step 4: Run Your Main Script
Now, you can run your main script, and it will have access to the functions defined in your common_functions.sh.
bash
bash ~/main_script.sh
Summary
Store reusable code blocks (functions) in a separate script (e.g., common_functions.sh).
Use the source command to include this file in your main script.
Call your functions as needed in the main script.
Notes
If you update your common_functions.sh, those updates will be reflected in any script where you have sourced it.
Make sure that the paths to your files are correct based on the structure of your directories. Adjust paths as necessary.
User
ok i do as you said. My main script have a for loop in it. An my functions script has connection check function in it. I want my main script to check connection but if there is no connection then stop and go to other item in the for loop.
Assistant
To achieve this, you can modify your functions in the common_functions.sh file to return a specific exit status indicating whether the connection check was successful or not. Then, in your main script, you can use that exit status to decide whether to continue with the current iteration of the loop or skip to the next item.
Step 1: Update your Functions Script
Open your common_functions.sh file:
bash
nano ~/common_functions.sh
Update the connection check function to return an appropriate exit status. Here’s an example of how you might implement this with a simple connection check (e.g., pinging a server):
bash
#!/bin/bash
function check_connection {
local host="$1"
ping -c 1 "$host" &> /dev/null
if [[ $? -eq 0 ]]; then
return 0 # Success
else
return 1 # Failure
fi
}
Save and close the file.
Step 2: Update Your Main Script
Open your main_script.sh:
bash
nano ~/main_script.sh
Implement the for loop with the connection check. Here’s an example:
bash
#!/bin/bash
# Source the common functions
source ~/common_functions.sh
# List of hosts to check
hosts=("8.8.8.8" "192.168.1.1" "nonexistent.host")
for host in "${hosts[@]}"; do
echo "Checking connection to $host..."
# Call the check_connection function
check_connection "$host"
# Check exit status of the previous command
if [[ $? -ne 0 ]]; then
echo "No connection to $host, skipping to the next item."
continue # Skip to the next item in the loop
fi
echo "Connected to $host."
# Place other operations that depend on the connection here
done
User
i want that if [[ $? -ne 0 ]]; then continue part to be in the functions script too. can it be done
Assistant
Yes, you can certainly encapsulate the logic for handling the connection check within the function itself. This way, the function will be responsible for both performing the check and deciding whether to continue the loop based on the result.
Step 1: Update your Functions Script
You can modify the check_connection function to accept both the host and the condition to continue the loop. The function would return an error status if the connection check fails, and you can check this status in the main script to control the loop behavior.
Here’s how you can adjust the common_functions.sh:
bash
#!/bin/bash
function check_connection {
local host="$1"
local should_continue="$2"
ping -c 1 "$host" &> /dev/null
if [[ $? -eq 0 ]]; then
echo "Connected to $host."
return 0 # Success
else
echo "No connection to $host."
if [[ "$should_continue" == "true" ]]; then
return 1 # Failure, and signal to continue in the for loop
else
exit 1 # Failure and exit if should_continue is not set to true
fi
fi
}
Step 2: Update Your Main Script
Now, modify the main_script.sh to use this updated function:
bash
#!/bin/bash
# Source the common functions
source ~/common_functions.sh
# List of hosts to check
hosts=("8.8.8.8" "192.168.1.1" "nonexistent.host")
for host in "${hosts[@]}"; do
echo "Checking connection to $host..."
# Call the check_connection function with continue option set to true
check_connection "$host" "true"
# Check exit status of the check_connection only for handling cases
if [[ $? -ne 0 ]]; then
echo "Skipping to the next item."
continue # Skip to the next item in the loop
fi
# If connection was successful, you can perform other operations here
# ...
done
User
But you are still giving continue part in the main script.
Assistant
If you want to fully encapsulate the logic, including the continue, within the function itself, we can change the function to handle both the connection check and the control flow. However, this means that the function needs to know what to do when it fails—in this case, that it should skip to the next iteration in the loop.
Here’s how you can set it up:
Step 1: Update your Functions Script
You'll modify the check_connection function to take care of the loop control inside the function itself. This can be accomplished by using a combination of return values and a custom behavior in the function.
bash
#!/bin/bash
function check_connection {
local host="$1"
ping -c 1 "$host" &> /dev/null
if [[ $? -eq 0 ]]; then
echo "Connected to $host."
return 0 # Success
else
echo "No connection to $host."
return 1 # Failure
fi
}
function handle_host {
local host="$1"
# Try connecting and handle the result
check_connection "$host"
if [[ $? -ne 0 ]]; then
echo "Skipping to the next item."
return 1 # Signal to skip to the next item
fi
# If connected, you can run other operations here
# ...
}
Step 2: Update Your Main Script
Now, you can simplify your main script to use the handler function:
bash
#!/bin/bash
# Source the common functions
source ~/common_functions.sh
# List of hosts to check
hosts=("8.8.8.8" "192.168.1.1" "nonexistent.host")
for host in "${hosts[@]}"; do
echo "Checking connection to $host..."
# Call the handle_host function; it handles the connection check and loop control
handle_host "$host" || continue # If the connection fails, go to the next item
done
Explanation
Function Definitions:
User
cant i put continue command in the functions too
Assistant
In Bash, you cannot directly use the continue statement inside a function to affect the for-loop that called it; continue applies to the loop that is currently executing. However, you can handle the loop control within the function by using the return status of the function, which is the idiomatic way of doing this in Bash scripting.
That said, if you want to use a function to encapsulate logic, while still achieving a continue-like behavior, you can accomplish it by using a return status to signal success or failure, and then handle the continue in the main script based on that return status.
Here’s a common way you can achieve this while still keeping your main script clean:
Approach
The function will perform the connection check and return a status.
The main script will use this return status to decide on continuing the loop.
Step 1: Function Script - Check Connection
Here’s how you can structure the function script (common_functions.sh):
bash
#!/bin/bash
function check_connection {
local host="$1"
ping -c 1 "$host" &> /dev/null
if [[ $? -eq 0 ]]; then
echo "Connected to $host."
return 0 # Success
else
echo "No connection to $host."
return 1 # Failure
fi
}
function handle_host {
local host="$1"
# Call the check_connection function
check_connection "$host"
# Check the exit status of the connection check
if [[ $? -ne 0 ]]; then
# If there is no connection, return 1 to signal to continue
return 1 # Indicate that we should skip this host
fi
# If you're connected, you can perform other operations here
# ...
}
Step 2: Main Script - Use the Function
Now, modify your main script (main_script.sh) to use the handle_host function:
bash
User
I have below code both checkConnection and checkAccess are dunctions. if first fails i want it to return1 and do not continue the other function
function checkHost() {
checkConnection
checkAccess
if [[ connectionResult = 0 && accessResult = 0 ]] ; then lecho 0 "$hostName looks fine."
}
Assistant
To achieve your requirement where if the first function checkConnection fails, it should return 1 and not proceed to call the second function checkAccess, you need to incorporate the return value checks directly after each function call within the checkHost function.
You can do this by modifying the checkHost function to check the result of checkConnection before calling checkAccess. Here's how you can structure your code:
bash
#!/bin/bash
function checkConnection() {
# Simulating a check; replace with your actual logic
# e.g., ping or any other connectivity check
# Set result for demonstration purposes
connectionResult=0 # Assume success; set to 1 to simulate failure
return $connectionResult
}
function checkAccess() {
# Simulating a check; replace with your actual logic
accessResult=0 # Assume success; set to 1 to simulate failure
return $accessResult
}
function checkHost() {
# Call checkConnection and store its result
checkConnection
connectionResult=$? # Capture the exit status of checkConnection
# Check whether the connection check succeeded
if [[ $connectionResult -ne 0 ]]; then
echo "Connection check failed."
return 1 # Return 1 to indicate failure
fi
# Call checkAccess only if connection check is successful
checkAccess
accessResult=$? # Capture the exit status of checkAccess
# Check whether the access check succeeded
if [[ $accessResult -ne 0 ]]; then
echo "Access check failed."
return 1 # Return 1 to indicate failure
fi
echo "$hostName looks fine."
return 0 # Successful completion of all checks
}
# Example usage
hostName="example.com"
checkHost
if [[ $? -ne 0 ]]; then
echo "Host checks failed for $hostName."
else
echo "Host checks passed for $hostName."
fi
User
i use below code for checkAccess but when i give wrong password below ?is0.howtochecksothatitistimeoutorwronguserorwrongpasswordorportectecho"ldapUser/ldapPassword@hostName:port/serviceName > /dev/null 2>&1
Assistant
When using sqlplus or any similar command and you want to handle errors (like wrong username/password, timeout, etc.), you'll need to capture the exit status and the output of the command properly. The approach you've shown pipes the string "exit" into sqlplus, but it doesn't provide a way to check if the connection was successful or if there was an error with the login credentials.
Here’s how you can modify the command to check for connection issues, including wrong username/password, timeout, or incorrect connection strings.
Using sqlplus with Error Checking
You can use the sqlplus command and evaluate its output to determine if the connection was successful. Here's a way to approach this:
Redirection: Redirect both the output and error messages to a variable.
Evaluate the result: Check for specific error messages in the output variable after running the command.
Here's an example of how you could implement it:
bash
function checkAccess() {
local ldapUser="$1"
local ldapPassword="$2"
local hostName="$3"
local port="$4"
local serviceName="$5"
# Execute sqlplus and capture output
output=$(echo "exit" | timeout 15 sqlplus64 -s "$ldapUser/$ldapPassword@$hostName:$port/$serviceName")
# Check if sqlplus returned an error or if output contains specific failure messages
if [[ $? -ne 0 ]]; then
echo "SQL*Plus command timed out."
return 1
fi
# Check output for known error messages
if [[ $output == *"ORA-01017"* ]]; then
echo "Error: Invalid username/password."
return 1
elif [[ $output == *"ORA-12154"* ]]; then
echo "Error: TNS:could not resolve the connect identifier specified."
return 1
elif [[ $output == *"ORA-12541"* ]]; then
echo "Error: TNS:no listener."
return 1
fi
# If no errors, the connection is successful.
echo "Access check succeeded."
return 0
}
User
give me your style of oracle db access check
Assistant
Certainly! When implementing an Oracle Database access check using the sqlplus command, it's important to create a clear and structured approach. Below is a Bash function that encapsulates the logic for checking access, handles errors gracefully, and provides useful output.
Oracle Database Access Check Function
bash
#!/bin/bash
function checkOracleAccess() {
local ldapUser="$1"
local ldapPassword="$2"
local hostName="$3"
local port="$4"
local serviceName="$5"
# Build the connection string
local connectionString="$ldapUser/$ldapPassword@$hostName:$port/$serviceName"
# Execute sqlplus command and capture output
output=$(echo "exit" | timeout 15 sqlplus64 -s "$connectionString" 2>&1)
# Check if sqlplus returned an error (timeout or other issues)
if [[ $? -ne 0 ]]; then
echo "SQL*Plus command timed out or failed to start."
return 1
fi
# Check output for known Oracle error codes
if echo "$output" | grep -q "ORA-01017"; then
echo "Error: Invalid username/password."
return 1
elif echo "$output" | grep -q "ORA-12154"; then
echo "Error: TNS:could not resolve the connect identifier specified."
return 1
elif echo "$output" | grep -q "ORA-12541"; then
echo "Error: TNS:no listener."
return 1
elif echo "$output" | grep -q "ORA-28009"; then
echo "Error: The password has expired."
return 1
fi
# If we reach this point, the connection was successful
echo "Access check succeeded for $hostName:$port."
return 0
}
# Example usage
ldapUser="your_user"
ldapPassword="your_password"
hostName="your_hostname"
port="your_port"
serviceName="your_service_name"
checkOracleAccess "$ldapUser" "$ldapPassword" "$hostName" "$port" "$serviceName"
if [[ $? -ne 0 ]]; then
echo "Access check failed."
else
echo "Access check passed."
fi
When you run your main_script.sh, it will check the connection for each host in the list. If there is no connection to a host, the script will print a message and continue to the next host:
bash
bash ~/main_script.sh
How It Works
The function check_connection checks if the provided host is reachable via ping.
When the connection check is called in your main script, it will return 0 (success) or 1 (failure).
The exit status of the connection check is evaluated using if [[ $? -ne 0 ]]; then to determine if there's a connection. If there isn’t, it uses the continue statement to skip to the next iteration of the loop.
This structure allows your main script to handle connection checks efficiently while iterating over multiple hosts.
Explanation
Function Definition (check_connection):
The function takes two parameters: the host to check and a flag (should_continue).
It checks whether the host is reachable using ping.
If the ping fails, it checks if it should continue. If should_continue is "true", the function returns an error status (return 1), allowing the main script to continue to the next iteration. If should_continue is false or not given, it exits the entire script with exit 1.
Main Script:
The main script calls check_connection with a value of "true" for the should_continue parameter.
It checks the function exit status to determine if it should proceed or skip to the next item in the list.
Summary
This structure keeps your main script clean while delegating the logic for connection management to the function. You can easily modify the behavior of the check_connection function to suit your needs without changing the logic in the main script.
check_connection: This function checks if the given host is reachable (using ping). It returns a success or failure status.
handle_host: This function handles the connection check for each host. If check_connection fails, it outputs a message and returns a non-zero status, indicating an error.
Main Script:
The main script iterates over the list of hosts and calls handle_host.
The || continue construct checks the exit status of handle_host. If it returns a non-zero status (indicating the connection check failed), the loop continues to the next item, effectively handling flow control within the defined functions.
Summary
This approach encapsulates the connection handling logic within a dedicated function (handle_host). This function now manages both the connection check and the decision to skip to the next iteration, thus simplifying your main script without having explicit continue statements in it.
#!/bin/bash
# Source the common functions
source ~/common_functions.sh
# List of hosts to check
hosts=("8.8.8.8" "192.168.1.1" "nonexistent.host")
for host in "${hosts[@]}"; do
echo "Checking connection to $host..."
# Call the handle_host function and check its exit status
if ! handle_host "$host"; then
echo "Skipping to the next item."
continue # If handle_host returns non-zero, skip to the next iteration
fi
# If there's a successful connection, perform operations
echo "Now performing operations on $host."
# ... other operations can go here
done
Explanation
Function Definitions:
check_connection: This function checks connectivity to the provided host.
handle_host: This function calls check_connection and checks its result. If the connection fails, it returns a non-zero status to indicate the caller should skip this iteration.
Main Script:
The for loop iterates over the list of hosts.
When handle_host is called, it will return a status based on the ping success.
The if ! handle_host "$host"; syntax checks if the return status is not 0 (indicating failure), and if so, it executes continue, skipping to the next host.
Summary
While you can't directly include a continue statement within a function to affect the loop where it was called, using return statuses to control flow is a common pattern in Bash scripting. The structure above helps keep your main script cleaner while still encapsulating the connection logic in dedicated functions.
Explanation of the Code:
Function checkConnection: Simulates a connection check. You would replace the logic here with actual connection-checking code. The exit status is set implicitly by the return statement.
Function checkAccess: Also simulates an access check and works similarly to checkConnection.
Function checkHost:
Calls checkConnection and stores its exit status in connectionResult.
It checks if connectionResult is not equal to 0, meaning the connection check failed. If it did, it echoes an error message and returns 1, stopping further execution of the function.
If the connection check succeeds, it calls checkAccess, stores its status in accessResult, and performs a similar check.
If both checks pass, it echoes a success message.
Example Usage: After defining all functions, you call checkHost and then check its exit status to determine whether to proceed or indicate failure.
Summary
With this setup, if checkConnection fails, the checkHost function will return 1 immediately, and checkAccess will not be called. This adheres to your requirement to stop execution upon a failure during the first check.
e
x
i
t
"∣
t
im
eo
u
t
15
s
q
l
pl
u
s
64
Explanation
Timeout Handling: The timeout 15 command makes sure that if the sqlplus command does not complete within 15 seconds, it will automatically terminate. The exit status of the timeout command will be non-zero if it timed out.
Capturing Output: The output of sqlplus is captured into a variable output. This allows you to evaluate its content later.
Error Checking: After capturing the output, the code checks:
If the return status of the last command ($?) is non-zero, it means something went wrong (like a timeout).
If output contains specific Oracle error codes, such as ORA-01017 for invalid username/password, it prints an appropriate error message.
Return Value: The function returns 0 for a successful connection and 1 for any failure, ensuring you can handle that in your main script.
Usage Example
You'd call the checkAccess function like this, passing your parameters:
bash
ldapUser="your_user"
ldapPassword="your_password"
hostName="your_hostname"
port="your_port"
serviceName="your_service_name"
checkAccess "$ldapUser" "$ldapPassword" "$hostName" "$port" "$serviceName"
if [[ $? -ne 0 ]]; then
echo "Access check failed."
else
echo "Access check passed."
fi
This method allows you to effectively manage and check for various conditions that could cause the sqlplus command to fail, making your error handling much more robust. Remember to replace the Oracle error codes with those that are relevant to your specific database and environment, and adjust the error messages as needed.
Explanation of the Function
Parameters: The function takes five parameters: ldapUser, ldapPassword, hostName, port, and serviceName. These parameters are necessary to form the connection string.
Connection String: The connection string is built as ldapUser/ldapPassword@hostName:port/serviceName.
Executing the Command:
The command echo "exit" | timeout 15 sqlplus64 -s "$connectionString" 2>&1 is executed.
The -s flag is used with sqlplus to suppress unnecessary output (like the banner and prompts).
The output, including any error messages, is captured in the variable output.
Timeout Handling: The exit status of the command is checked:
If it is not zero, it indicates that the command failed to execute or timed out.
Error Checking: The output is checked for various Oracle-specific error messages using grep:
It checks for error codes corresponding to invalid username/password, connectivity issues, and other relevant errors.
Success Message: If no errors are found in the output, the function echoes a success message indicating that the access check succeeded.
Usage Example
In the example usage, simply replace the connection parameters (ldapUser, ldapPassword, hostName, port, and serviceName) with the appropriate values for your Oracle Database.
Summary
This structured approach to checking Oracle Database access using sqlplus ensures that you capture and handle various errors that may arise during the connection attempt. It provides clear feedback to the user based on the nature of the error, making it easier to diagnose connection issues. Feel free to modify the error messages and checks based on your specific Oracle version and setup.