← Back to Bash Course | Chapter 8: Input/Output & Redirection | Lesson 1 of 13

Function की Basics

एक function एक recipe card जैसा है जो आप एक बार लिखते हैं और बार-बार उपयोग करते हैं। आप इसे एक नाम देते हैं, और हर बार जब आप वह नाम बोलते हैं computer steps follow करता है।

In this page:

  1. Function Basics
Syntax
bash
function_name() {
  commands
}
function_name

Function Basics

एक Bash function function_name() { ... } उपयोग करके commands को एक नाम के तहत group करता है, आपको same logic बिना code duplicate किए बार-बार call करने देते हुए।

Functions को script में call होने से पहले define होना चाहिए। ये किसी भी दूसरे command की तरह ही invoke होते हैं, उनका नाम लिखकर।

Note: नाम से पहले function keyword Bash में optional है — greet() { ... } और function greet { ... } दोनों काम करते हैं।

उदाहरण: Function Basics

bash
#!/bin/bash
greet() {
    echo "Hello from a function!"
}

greet
greet
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. greet() { ... } लिखना और फिर इसे greet() के रूप में call करना, जब यह सिर्फ greet से call होता है।
  2. एक function को इसके definition से पहले call करना।
  3. एक existing command जैसे ही नाम वाला function redefine करना, जो script में उस command को hide कर देता है।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.